首页 > 代码库 > leetcode链表--16、swap-nodes-in-pairs(成对交换链表结点)

leetcode链表--16、swap-nodes-in-pairs(成对交换链表结点)

题目描述
 
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
 
解题思路:与15题一样,只是k为2,也是使用栈结构进行存储。
1)当tmp<k时,将p插入到栈中,tmp==k是弹出栈,存入新链表中
2)如果最后栈中还有元素,即剩一个,则将其存入令一个栈中,然后将那个栈弹出存入新链表中
3)返回head->next
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *swapPairs(ListNode *head) {
12         if(head == NULL)
13             return NULL;
14         int k = 2;
15         stack<ListNode *> s;
16         ListNode *p = head;
17         ListNode *newHead = new ListNode(0);
18         ListNode *newP = newHead;
19         int tmp = 0;
20         while(p != NULL)
21         {
22             if(tmp<k)
23             {
24                 s.push(p);
25                 p = p->next;
26                 tmp++;
27             }
28             if(tmp == k)
29             {
30                 while(!s.empty())
31                 {
32                     newP->next = s.top();
33                     s.pop();
34                     newP = newP->next;
35                     tmp--;
36                 }
37             }
38  
39         }
40         stack<ListNode *>s2;
41         while(!s.empty())
42         {
43             s2.push(s.top());
44             s.pop();
45         }
46         while(!s2.empty())
47         {
48             newP->next = s2.top();
49             s2.pop();
50             newP = newP->next;
51         }
52         newP->next = NULL;
53         return newHead->next;
54     }
55 };

 

leetcode链表--16、swap-nodes-in-pairs(成对交换链表结点)