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.

 

思路:

  以1->2->3->4为例,为了方便计算首先添加一个头节点0,此时链表为0->1->2->3->4。题目要求两两节点相互交换,则最终的链表应该为0->2->1->4->3。

  首先关注节点1和2的交换。节点0为prev,节点1为cur,具体操作步骤为:

  • pre->next = cur->next;
  • cur->next = cur->next->next;
  • pre->next->next = cur;

  通过这样的操作后,此时链表为0->2->1->3->4。接下来是节点3和节点4的交换操作。具体步骤与节点1和节点2的交换步骤相一致,为了重复这一过程,需要更新prev和cur。具体操作步骤为:

  • pre = cur;
  • cur = cur->next;

 

代码:

 1 class Solution {
 2 public:
 3     ListNode* swapPairs(ListNode* head) {
 4         if (head == NULL || head->next == NULL)
 5             return head;
 6         ListNode* newhead = new ListNode(0);
 7         newhead->next = head;
 8         ListNode* pre = newhead;
 9         ListNode* cur = head;
10         while (cur && cur->next) {
11             pre->next = cur->next;
12             cur->next = cur->next->next;
13             pre->next->next = cur;
14             pre = cur;
15             cur = cur->next;
16         }
17         return newhead->next;
18     }
19 };

 

posted @ 2017-06-02 21:17  Sindyang  阅读(155)  评论(0编辑  收藏  举报