LeetCode刷题记录NO.24 交换链表节点
题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
来源:LeetCode
基本思路
迭代
直接观察可以知道,每交换一次链表,实际上涉及到四个数据的操作,如
1->2->3->4
交换之后为
2->1->4->3
具体步骤:
2指向1,1指向4,4指向3,3指向下一组数据的第二个元素。
但是链表可能为偶数可能为奇数,如果为偶数,刚好凑成一组;如果为奇数,最后会剩下一个单独的元素,让上一组数据的指针直接指向这个元素即可。
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null) return null;
if(head!=null && head.next==null) return head;
ListNode res = head.next;
ListNode cur = head;
ListNode first = cur;
ListNode second = cur.next;
while(cur.next!=null && cur.next.next!=null){
cur = cur.next.next;
second.next = first;
if(cur.next==null){
first.next = cur;
return res;
}
else first.next = cur.next;
first = cur;
second = cur.next;
}
cur.next.next = cur;
cur.next = null;
return res;
}
}
递归
利用迭代思想的代码过于复杂,且需要考虑空链表、奇偶数等各种情况,下面利用迭代思想解决
递归出口:链表无节点或者只剩一个节点,此时不需要交换,直接返回null/该节点即可。
递归体:链表中有至少两个节点,则交换这两个节点,交换之后,返回新链表的表头(原链表的第二个节点)。下面代码用first和second表示原链表的第一个和第二个节点。
class Solution {
public ListNode swapPairs(ListNode head){
if(head==null||head.next == null) return head;
ListNode first = head;
ListNode second = head.next;
first.next = swapPairs(second.next);
second.next = first;
return second;
}
}