-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
94 lines (82 loc) · 2.28 KB
/
LinkedList.java
File metadata and controls
94 lines (82 loc) · 2.28 KB
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
90
91
92
93
94
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public class LinkedList {
public ListNode middleNode(ListNode head) {
ListNode temp = head, tempc = head;
while (tempc != null && tempc.next != null) {
temp = temp.next;
tempc = tempc.next.next;
}
return temp;
}
public ListNode reverseList(ListNode head) {//for the diagram visit https://youtu.be/G0_I-ZF0S38?t=118
ListNode curr = head, prev = null, temp;
while (curr != null) {
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
public static ListNode deleteDuplicates(ListNode head) {
ListNode curr = head;
while (curr != null && curr.next != null) {
if (curr.val == curr.next.val) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return head;
}
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode out = new ListNode(0), dum = out, p1 = list1, p2 = list2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
dum.next = p1;
p1 = p1.next;
} else {
dum.next = p2;
p2 = p2.next;
}
dum = dum.next;
}
if (p1 != null) {
dum.next = p1;
}
if (p2 != null) {
dum.next = p2;
}
return out.next;
}
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode s = head, f = head;
while (f != null && f.next != null) {
s = s.next;
f = f.next.next;
if (f==s) {
return true;
}
}
return false;
}
public static void main(String[] args) {
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));
System.out.println(deleteDuplicates(head));
}
}