题目:
Given a linked list, swap every two adjacent nodes and return its head.
例子:
Example 1:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
问题解析:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
相似题:
- Reverse Nodes in k-Group
思路标签
栈的思想
解答:
栈
- 和第25题是相似的题目,因为链表是以k长度,这里(k=2)进行翻转,所以最后生成的链表是k大小的先进后出,则明显可以以栈的形式来实现。
- 注意要加一个返回链表头节点的指针的指针。
- 同时需要处理末尾最后小于k的节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
stack<ListNode*> k;
ListNode *cur = head, *lead = new ListNode(0), *prv =lead;
while(cur){
if(k.size()==2){
while(k.size()){
prv->next = k.top();
k.pop();
prv = prv->next;
prv->next = NULL;
}
}
k.push(cur);
cur = cur->next;
}
while(k.size()){
prv->next = k.top();
k.pop();
prv = prv->next;
prv->next = NULL;
}
return lead->next;
}
};