LeetCode 24. Swap Nodes in Pairs | 交换两个node(链表)
链表交换两个node
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3
交换相邻两个链表节点。
C++版本。
/**
* 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) {
ListNode *tmp=new ListNode(0);
tmp->next = head;
ListNode *ans=tmp;
while(tmp->next && tmp->next->next){
ListNode *tt = new ListNode(tmp->next->val);
tmp->next = tmp->next->next;//删除前一个
tt->next = tmp->next->next;//指向下一对
tmp->next->next = tt;
tmp = tmp->next->next;
}
return ans->next;
}
};