-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyLinkedList.java
88 lines (74 loc) · 2.24 KB
/
MyLinkedList.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
package com.interview.notes.code.linkedlist;
public class MyLinkedList {
private Node head;
public static void main(String[] args) {
MyLinkedList linkedList = new MyLinkedList();
linkedList.insertFirst(100);
linkedList.insertFirst(500);
linkedList.insertFirst(300);
linkedList.insertFirst(200);
linkedList.printLinkedList();
//linkedList.deleteFirst();
// linkedList.printLinkedList();
// linkedList.insertLast(7000);
// linkedList.printLinkedList();
linkedList.lengthOfLinkedList();
System.out.println(linkedList.lengthOfLinkedList());
//linkedList.printLinkedList();
//Node nthNodeFromLast= linkedList.nthFromLastNode(head,3);
//System.out.println("3th node from end is : "+ nthNodeFromLast.value);
}
public boolean isEmpty() {
return (head == null);
}
public void insertFirst(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
}
public void insertLast(int data) {
Node current = head;
while (current.next != null) {
current = current.next;
}
Node newNode = new Node();
newNode.data = data;
current.next = newNode;
}
public Node deleteFirst() {
Node temp = head;
head = head.next;
return temp;
}
public Node nthFromLastNode(Node head, int n) {
Node firstPointer = head;
Node secondPointer = head;
for (int i = 0; i < n; i++) {
firstPointer = firstPointer.next;
}
while (firstPointer != null) {
firstPointer = firstPointer.next;
secondPointer = secondPointer.next;
}
return secondPointer;
}
public int lengthOfLinkedList() {
Node temp = head;
int count = 0;
while (temp != null) {
temp = temp.next;
count++;
}
return count;
}
public void printLinkedList() {
Node current = head;
Node node = new Node();
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
}