forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwappingNodesInALinkedList.java
89 lines (77 loc) · 1.89 KB
/
SwappingNodesInALinkedList.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// @saorav21994
// TC : O(n)
// SC : O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapNodes(ListNode head, int k) {
int i = 1;
ListNode cur = head;
while (i < k) {
cur = cur.next;
i += 1;
}
ListNode tmp1 = cur;
int n = k;
while (cur.next != null) {
n += 1;
cur = cur.next;
}
// System.out.println("n=" + n);
cur = head;
k = n-k;
i = 0;
while (i < k) {
cur = cur.next;
i += 1;
}
// System.out.println(tmp1.val);
int tmp2 = cur.val;
cur.val = tmp1.val;
tmp1.val = tmp2;
return head;
}
}
// Author: @romitdutta10
// TC : O(n)
// SC : O(1)
// Problem : https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode first = null;
ListNode slow = head;
ListNode fast = head;
int count = 1;
while(count < k) {
fast = fast.next;
count++;
}
first = fast;
while(fast.next != null) {
slow = slow.next;
fast = fast.next;
}
int temp = first.val;
first.val = slow.val;
slow.val = temp;
return head;
}
}