题目:leetcode 24.Swap Nodes in Pairs
链接:https://leetcode.com/problems/swap-nodes-in-pairs/#/description
原题:
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.
解题思路:这题也是出于想重新拾回c++链表数据结构的原因才做的,做的时候发现指针这东西非常难,虽然题目大意简单,每两个相邻的节点互换,但实现起来关于指针的内容十分容易让人混淆。换位的第一技巧就是生成一个temp, temp = a, a=b, b=temp。在这题也一样,但唯一最重要的点是,当b=temp这一步是要将上一个节点的next指向temp的时候就有问题了,我们需要记录的存有那个next的节点,具体看代码。另外再附上一份思路效果跟我相同,但是比我简洁的代码。
代码:
/**
* 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 || !head->next){
return head;
}
ListNode* temp = head->next;
//temp = head.next;
head->next = head->next->next;
temp->next = head;
head = temp;
ListNode *h = head->next;
//ListNode *h1 = h->next;
while(h->next && h->next->next){
temp = h->next->next;
h->next->next = h->next->next->next;
temp->next = h->next;
h->next = temp;
h = h->next->next;
}
return head;
}
};
ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) {
a->next = b->next;
b->next = a;
*pp = b;
pp = &(a->next);
}
return head;
}