力扣24(java&python)-两两交换链表中的节点(中等)

题目:

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)

示例 1:

 

 输入:head = [1,2,3,4]

输出:[2,1,4,3]

示例2:

输入:head = []

输出:[]

示例 3:

输入:head = [1]

输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100] 内
  • 0 <= Node.val <= 100

解题思路:

递归:题中是两两交换结点,都是重复的步骤就想到了递归。

主要思考三点:

1.返回值是什么?

最终交换完成的子链表

2.具体怎么做?

设两个需要交换的结点一个为head,一个为next,head主要负责连接后面完成交换的链表,next负责连接head。

3.终止条件是什么?

当需要交换的链表为空结点或者无后继结点即head为空指针或者next为空指针时,无法进行交换操作就停止。

举例:head = [1,2,3,4,5,6]

1.首先需要明白这六个数,两两进行分组的(如果是奇数,最后一次递归没有两个结点,就返回最后一个结点就行);

2.(1,2),(3,4),(5,6),head指向下一层的递归函数,next作为头结点,递归到(5,6)时后续没有结点了,就开始交换5和6;

3.然后(3,4)开始交换,3指向交换后的链表,4作为暂时的头结点;

4.最后(1,2)开始交换,1指向后面全部完成交换的链表,2作为最终的头结点。

 java代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode swapPairs(ListNode head) {
13         //当结点为空或只有头结点
14         if(head == null || head.next == null) return head;
15         //保存头结点的下一个结点
16         ListNode temp = head.next;
17         //让后续结点递归交换,让头结点进行连接
18         head.next = swapPairs(temp.next);
19         //头结点的下一个结点反向连接头结点
20         temp.next = head;
21         //返回链表
22         return temp;
23 
24     }
25 }

 

 pyhthon3代码:

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, val=0, next=None):
 4 #         self.val = val
 5 #         self.next = next
 6 class Solution:
 7     def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
 8         if  not head or not head.next:
 9             return head
10         
11         temp = head.next
12         # 使用self参数调用swapPairs()方法
13         head.next = self.swapPairs(temp.next)
14         temp.next = head
15         return temp

2023-05-04:直接模拟

 1 //模拟
 2 class Solution {
 3     public ListNode swapPairs(ListNode head) {
 4         if (head == null || head.next == null) return head;
 5         ListNode dummyHead = new ListNode(-1);
 6         dummyHead.next = head;
 7         ListNode cur = dummyHead;
 8         //节点个数为奇数或者偶数时
 9         while (cur.next != null && cur.next.next != null){
10             //保存当前组的第一个节点,例如1
11             ListNode temp1 = cur.next;
12             //保存下一组的第一个节点,例如3
13             ListNode temp2 = cur.next.next.next;
14             //虚拟头结点指向2
15             cur.next = cur.next.next;
16             //2->1
17             cur.next.next = temp1;
18             //1->3
19             temp1.next = temp2;
20             //移动cur指向下一组的前一个节点,就是节点1
21             cur = temp1;
22         }
23         return dummyHead.next;
24     }
25 }

 

posted on 2022-09-17 11:39  我不想一直当菜鸟  阅读(53)  评论(0编辑  收藏  举报