且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

leetcode 24 -- Swap Nodes in Pairs

更新时间:2022-09-18 08:34:33

Swap Nodes in Pairs

题目: 
Given a linked list, swap every two adjacent nodes and return its head. 
For example, 
Given 1->2->3->4, you should return the list as 2->1->4->3. 
Your algorithm should use only constant space. You may not modify the 
values in the list, only nodes itself can be changed.


题意: 
给你一个链表,交换两两节点,要求不能交换值,必须改变指针。 
1->2->3->4 变为 2->1->4->3


思路: 
注意保存pre先前的指针,还要注意特殊情况,有0个或者1个节点。以及链表长度为奇数的情况。


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */public**//特殊情况,0个或1个节点if==NULL||->==NULLreturn*=*=->//两个节点的情况if->==NULL->=->=NULL=return*=->*=while!=NULL&&!=NULL//改变指针指向=->=->=//向前跳转=->if==NULL==->->=//处理奇数节点的情况if==NULL->=->=->=NULLreturn