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

Leetcode 24 Swap Nodes in Pairs

时间:2015-04-14 07:10:45      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

/**
* ID: 24
* Name: Swap Nodes in Pairs
* Data Structure: Linked List
* Time Complexity:
* Space Complexity:
* Tag: LinkList
* Difficult: Medium

* Problem:
* Given a linked list, swap every two adjacent nodes and return its head.
* 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.

思路一: 

使用 pre, start , then方法,来处理反转,插入的操作,然后注意整个数组的长度是偶数还是奇数。 

 1 class Solution {
 2 public:
 3     ListNode *swapPairs(ListNode *head) {
 4         if(head==NULL || head->next == NULL)
 5             return head; 
 6         ListNode * fakeNode = new ListNode(0);
 7         fakeNode -> next = head; 
 8         ListNode * pre = fakeNode;
 9         ListNode * start = pre->next; 
10         ListNode * then = start -> next; 
11         while(then)
12         {
13             start -> next = then -> next; 
14             then -> next = pre ->next; 
15             pre->next = then;
16             then = start -> next; 
17             pre = start; 
18             if(pre->next==NULL)
19                 break;
20             start = start ->next; 
21             then = start->next; 
22         }
23         return fakeNode->next; 
24     }
25 };

思路二: 

 1 // recursive will be a little slower. 
 2 class Solution {
 3 public:
 4     ListNode *swapPairs(ListNode *head) {
 5         if(head==NULL || head->next == NULL)
 6             return head; 
 7         ListNode *next = head->next; 
 8         ListNode *nextnext = next->next;
 9         head ->next = this->swapPairs(nextnext);
10         next ->next = head; 
11         return next; 
12     }
13 };

 

Leetcode 24 Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/zhuguanyu33/p/4423866.html

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