题目:
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.
解答:/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
//如果没有节点或只有一个节点
if(head == NULL || head -> next == NULL) {
return head;
}
else {
ListNode *first, *second, *newHead = NULL, *pre = NULL;
first = head;
//second = head -> next;
while(first != NULL && first -> next != NULL) {
second = first -> next;
if(newHead == NULL) {
newHead = second;
}
first -> next = second -> next;
second -> next = first;
if(pre != NULL) {
pre -> next = second;
}
pre = first;
first = first -> next;
}
return newHead;
}
}
};
思路:
这道题没什么难度,容易忽略的就是只使用两个指针,即指向需要调换的两个元素,这样做是不够的,比如1→2→3→4,第一次调换为2→1→3→4,这时候两个指针应该指向3和4了,但是3、4调换完毕后,1的next仍指向3,导致错误,所以需要第三个指针,指向当前需要调换的两个元素的前一个元素,以便做好next的设置。