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

24. Swap Nodes in Pairs

时间:2016-06-01 23:11:14      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3 ListNode* swapPairs(ListNode* head) {
 4 ListNode *t1,*t2,*t3,*t4;
 5 if(head==NULL||head->next==NULL)
 6     return head;                   
 7 t4->next=t2->next;
 8 t3=t2->next->next;
 9 t2->next->next=t2;
10 t2->next=t3;
11 while(t2->next->next!=NULL)   
12 {
13 t1=t2->next;
14 t3=t2->next->next->next;
15 t2->next=t2->next->next;
16 t2->next->next=t1;
17 t1->next=t3;
18 t2=t1;
19 }
20 } 
21 }

 

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.

交换两个节点

思路:

很简单,就是三点

1、每次从交换节点的前一个节点开始

2、记录交换节点的后一个节点

3、交换两个节点

主要考察链表操作的逻辑

24. Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/wy-chen14/p/5550930.html

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