描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
例子
思路
- 递归:判断是否结点为空,或只剩一个结点,否则,首先保存second,不保存就找不到了,按如果操作,最后,返回second
- 迭代
答案 - python
//递归 简单快速
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
//有两个结点及以上
ListNode second = head.next;
head.next = swapPairs(second.next);
second.next = head;
return second;
}
}
//迭代
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
//cur为结果链表的最后一个结点
ListNode h = new ListNode(-1),cur=h;
h.next = head;
while(cur.next!=null && cur.next.next!=null) {
ListNode one = cur.next;
ListNode two = cur.next.next;
one.next = two.next;
two.next = one;
cur.next = two;
cur = cur.next.next;
}
return h.next;
}
}
//迭代2
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode h = new ListNode(-1),cur=h,pre=h;
int c = 1;
while(head!=null) {
ListNode temp = head.next;
if(c%2==1) {//当第奇数个时,采用尾插法
cur.next = head;
cur = cur.next;
//令新插入结点的next=null,防止有环
cur.next = null;
}else{//当第偶数个时,采用头插入,头是当前排好链表的倒数第二个
head.next = pre.next;
pre.next = head;
//用
pre = cur;
}
//下一个结点
head = temp;
//下次访问是第几个结点
c++;
}
return h.next;
}
}
*递归*
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
second=head.next
head.next=self.swapPairs(second.next)
second.next=head
return second
*迭代*
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
#因为要反转,所以给链表构造一个头结点
newHead = ListNode(0)
newHead.next = head
cur=newHead
while cur.next and cur.next.next:
# 因为改变链表的顺序,所以,先保存第一个不变的结点
first = cur.next
second = cur.next.next
first.next=second.next
second.next=first
cur.next=second
cur=cur.next.next
#如果还有一个结点,不用反转了
return newHead.next
- c++
*递归*
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
//如果为空,或者下一个结点为空,直接返回
if (!head || !head->next)
return head;
ListNode* second = head->next;
head->next = swapPairs(second->next);
second->next = head;
return second;
}
};
*迭代*
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* newHead = new ListNode(0);
newHead->next = head;
ListNode* cur=newHead;
while(cur->next && cur->next->next)
{
ListNode *first=cur->next, *second=cur->next->next;
first->next = second->next;
second->next = first;
cur->next = second;
cur=cur->next->next;
}
return newHead->next;
}
};