24. Swap Nodes in Pairs

 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、交换两个节点

主要考察链表操作的逻辑

posted on 2016-06-01 21:06  不小的文  阅读(119)  评论(0编辑  收藏  举报

导航