题目描述(中等难度)
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解法一 迭代
首先为了避免单独讨论头结点的情况,一般先申请一个空结点指向头结点,然后再用一个指针来遍历整个链表。
先来看一下图示:
point 是两个要交换结点前边的一个位置。
Java
class ListNode{
int val;
ListNode next;
ListNode(int val) {
this.val=val;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode point = dummy;
while(point.next!=null && point.next.next!=null) {
ListNode swap1 = point.next;
ListNode swap2 = point.next.next;
point.next=swap2;
swap1.next=swap2.next;
swap2.next=swap1;
point=swap1;
}
return dummy.next;
}
}
public static void main(String args[]) {
ListNode head=new ListNode(1);
ListNode p=head;
p.next=new ListNode(2);
p=p.next;
p.next=new ListNode(3);
p=p.next;
p.next=new ListNode(4);
ListNode ans=SwapPairs(head);
while(ans!=null) {
System.out.println(ans.val);
ans=ans.next;
}
}
}
时间复杂度:O(n)。
空间复杂度:O(1)。
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
point = dummy
while point.next!=None and point.next.next!=None:
swap1 = point.next
swap2 = point.next.next
point.next=swap2
swap1.next=swap2.next
swap2.next=swap1
point=swap1
return dummy.next
解法二 递归
递归的终止条件是链表中没有节点,或者链表中只有一个节点,此时无法进行交换。
如果链表中至少有两个节点,则在两两交换链表中的节点之后,原始链表的头节点变成新的链表的第二个节点,原始链表的第二个节点变成新的链表的头节点。链表中的其余节点的两两交换可以递归地实现。在对链表中的其余节点递归地两两交换之后,更新节点之间的指针关系,即可完成整个链表的两两交换。
Java
public static ListNode SwapPairs(ListNode head) {
if((head==null) || (head.next==null))
return head;
ListNode n=head.next;
head.next=SwapPairs(head.next.next);
n.next=head;
return n;
}
python
## Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
while head==None or head.next==None:
return head
n = head.next
head.next=self.swapPairs(head.next.next)
n.next=head;
return n
参考文献
- https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/liang-liang-jiao-huan-lian-biao-zhong-de-jie-di-91/