GuilinDev

Lc1721

05 August 2008

1721 Swapping Nodes in a Linked List

给一个k,左右两端的距离ends为k的两个nodes进行swap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Put slow at head, and put fast k-1 nodes after slow.
first = fast.
If fast isn't already at the last node, move slow and fast one node further until fast.next == null
second = slow
Swap the values of first and second ```java class Solution {
public ListNode swapNodes(ListNode head, int k) {		
    ListNode fast = head;
    ListNode slow = head;
    ListNode first = head, second = head;
    
	// Put fast (k-1) nodes after slow
    for(int i = 0; i < k - 1; ++i)
        fast = fast.next;
        
	// Save the node for swapping
    first = fast;

	// Move until the end of the list
    while(fast.next != null) {
		slow = slow.next;
        fast = fast.next;
    }
    
    // Save the second node for swapping
	// Note that the pointer second isn't necessary: we could use slow for swapping as well
	// However, having second improves readability
    second = slow;
	
	// Swap values
    int temp = first.val;
    first.val = second.val;
    second.val = temp;
    
    return head;
} } ```