LeetCode 24
Swap Nodes in Pairs
Problem Description:
在不改变结点值,直接对结点进行操作的前提下实现将链表相邻结点互换。
具体的题目信息:
https://leetcode.com/problems/swap-nodes-in-pairs/description/Solution: 关键在于对前驱结点的保存
/**
* 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)
return head;
if (head->next == NULL)
return head;
ListNode* r, *pre;
ListNode* p = head;
ListNode* q = head->next;
while(p && q) {
r = q->next;
q->next = p;
if (p == head) {
head = q;
} else {
pre->next = q;
}
p->next = r;
pre = p;
p = r;
if (p)
q = p->next;
}
return head;
}
};