1721.交换链表中的节点

题目描述

原题
给你链表的头节点 head 和一个整数 k
交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
示例 1:
1
输入:head = [1,2,3,4,5], k = 2
2
输出:[1,4,3,2,5]
Copied!
示例 2:
1
输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
2
输出:[7,9,6,6,8,7,3,0,9,5]
Copied!
示例 3:
1
输入:head = [1], k = 1
2
输出:[1]
Copied!
示例 4:
1
输入:head = [1,2], k = 1
2
输出:[2,1]
Copied!
示例 5:
1
输入:head = [1,2,3], k = 2
2
输出:[1,2,3]
Copied!
提示:
    链表中节点的数目是 n
    1 <= k <= n <= 105
    0 <= Node.val <= 100

题解

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 swapNodes(ListNode head, int k) {
13
//fast先走k步获取第k个
14
//创建slow两个一起走 fast为null时slow就等于倒数第k个
15
//然后就行交换
16
ListNode dummyNode = new ListNode();
17
dummyNode.next = head;
18
ListNode fast = dummyNode;
19
for(int i = 0;i < k && fast!=null ;i++){
20
fast = fast.next;
21
}
22
ListNode firstK = fast;
23
ListNode slow = dummyNode;
24
while(fast!=null){
25
fast = fast.next;
26
slow = slow.next;
27
}
28
ListNode lastK = slow;
29
//判断两个值是否相等 不相等就就进行交换
30
if(firstK.val != lastK.val){
31
int temp = firstK.val;
32
firstK.val = lastK.val;
33
lastK.val = temp;
34
}
35
return dummyNode.next;
36
}
37
}
Copied!
最近更新 3mo ago
复制链接