码迷,mamicode.com
首页 > 其他好文 > 详细

24. Swap Nodes in Pairs

时间:2017-06-02 22:01:51      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:节点   pac   use   blog   ons   style   sel   next   public   

题目:

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 };

 

24. Swap Nodes in Pairs

标签:节点   pac   use   blog   ons   style   sel   next   public   

原文地址:http://www.cnblogs.com/sindy/p/6935185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!