[ LeetCode ] #24. Swap Nodes in Pairs(交换相邻节点 C++ & Python)
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.
题意:
给一个单链表,返回相邻节点相互交换后的新链表。
分析:
如果不注意上面大大的note ,直接依次遍历交换相邻节点的值,即可得到结果。如Code1.
但既然题目要求必须使用交换节点,因此就需要对Code1进行相应的更改。
方法2:
以下为A,B节点交换的过程。pre用来保存当前交换节点的前驱节点,tmp指向当前交换前的左元素,post保存交换前tmp的下一元素。
- 使用临时变量post作为tmp的下一节点。
- 使tmp 的前一节点的 next 指向post。
- 使tmp的next指向post的下一节点,即可与后面未处理的链表连接起来。
- 使pre指向tmp,tmp指向tmp->next,即更新交换的位置。交换过程如下图。实现见Code2.
Code1 & 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) {
if(head==NULL)return head;
ListNode *tmp = head;
while(tmp->next != NULL){
ListNode *t = tmp->next;
swap(tmp->val, t->val);
if(t->next!=NULL)
tmp = t->next;
else
break;
}
return head;
}
};
结果:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 9.1 MB, less than 5.19% of C++ online submissions for Swap Nodes in Pairs.
Code2 & 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) {
if(head==NULL || head->next==NULL)return head;
ListNode *pre = head;
ListNode *tmp = pre->next;
pre->next = tmp->next;
tmp->next = pre;
head = tmp;
tmp = pre->next;
while(tmp!=NULL && tmp->next!=NULL){
ListNode *post = tmp->next;
pre->next = post;
tmp->next = post->next;
post->next = tmp;
pre = tmp;
tmp = pre->next;
}
return head;
}
};
结果:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 8.9 MB, less than 44.23% of C++ online submissions for Swap Nodes in Pairs.
Code2 & Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:return head
tmp = head.next
head.next = tmp.next
tmp.next = head
head = tmp
pre = tmp.next
tmp = pre.next
while tmp is not None and tmp.next is not None:
post = tmp.next
pre.next = post
tmp.next = post.next
post.next = tmp
pre = tmp
tmp = tmp.next
return head
结果:
Runtime: 36 ms, faster than 74.40% of Python3 online submissions for Swap Nodes in Pairs.
Memory Usage: 13.2 MB, less than 5.04% of Python3 online submissions for Swap Nodes in Pairs.