24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

该问题是链表的常见问题,可以认为是一种特殊的删除和插入操作,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* Node=head;
ListNode* pre=new ListNode(-1);
ListNode* Head=pre;
pre->next=Node;
while(Node && Node->next)
{
pre->next=Node->next;
ListNode* tmp=Node->next->next;
Node->next=tmp;
pre->next->next=Node;
pre=pre->next->next;
Node=tmp;
}
head=Head->next;
delete Head;
return head;
}
};
运行效果(找了一个最好的结果):

由于我多使用了一个前向节点,所以导致我的空间复杂度高了。下面是采用类似思路的Python实现代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return
hair=ListNode(-1)
hair.next=head
tmpHead=hair
while(head and head.next):
tmpNext=head.next.next
tmpHead.next=head.next
tmpHead.next.next=head
head.next=tmpNext
tmpHead=tmpHead.next.next
head=tmpHead.next
return hair.next
运行效果:

本文介绍了一种链表操作方法——两两交换相邻节点,通过C++与Python实现,展示了具体的代码细节及运行效果。
585

被折叠的 条评论
为什么被折叠?



