24. 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.

在不新建一个链表的情况下,交换链表相邻节点。

交换相邻节点A->B,A是head. 

ListNode* p = head;
head = head->next;
p->next = p->next->next;
head->next = p;

整体代码:

 1 class Solution {
 2 public:
 3     ListNode* swapPairs(ListNode* head) {
 4         if (!head || !head->next)
 5             return head;
 6         ListNode* p = head;
 7         head = head->next;
 8         p->next = p->next->next;
 9         head->next = p;
10         ListNode* q = p->next;
11         while (q && q->next) {
12             ListNode *temp = q;
13             q = q->next;
14             temp->next = temp->next->next;
15             q->next = temp;
16             p->next = q;
17             p = q->next;
18             q = p->next;
19         }
20         return head;
21     }
22 };

 

posted @ 2018-03-07 21:45  Zzz...y  阅读(113)  评论(0编辑  收藏  举报