[LeetCode] 1721. Swapping Nodes in a Linked List
You are given the head
of a linked list, and an integer k
.
Return the head of the linked list after swapping the values of the kth
node from the beginning and the kth
node from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5]
Example 2:
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5]
Example 3:
Input: head = [1], k = 1 Output: [1]
Example 4:
Input: head = [1,2], k = 1 Output: [2,1]
Example 5:
Input: head = [1,2,3], k = 2 Output: [1,2,3]
Constraints:
- The number of nodes in the list is
n
. 1 <= k <= n <= 105
0 <= Node.val <= 100
交换链表中的节点。
给你链表的头节点 head
和一个整数 k
。交换链表正数第 k
个节点和倒数第 k
个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
由于只需要swap两个节点的node.val,所以这道题简单很多。这里我提供一个双指针的思路。首先我们计算一下链表的长度len,得到这个长度之后,因为要交换的节点是正数第 K 个和倒数第 K 个节点,其中倒数第 K 个节点正数的index = len + 1 - k。依据这个信息,我们用两个指针从head节点开始遍历,分别在两个被swap的节点停下,swap他们的节点值即可。
时间O(n)
空间O(1)
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 swapNodes(ListNode head, int k) { 13 int len = 0; 14 ListNode cur = head; 15 while (cur != null) { 16 cur = cur.next; 17 len++; 18 } 19 20 int first = k; 21 int second = len + 1 - k; 22 int i = 1; 23 ListNode p = head; 24 while (p != null && i != first) { 25 p = p.next; 26 i++; 27 } 28 29 int j = 1; 30 ListNode q = head; 31 while (q != null && j != second) { 32 q = q.next; 33 j++; 34 } 35 36 int temp = p.val; 37 p.val = q.val; 38 q.val = temp; 39 return head; 40 } 41 }