-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInsertAtEnd
74 lines (61 loc) · 1.5 KB
/
InsertAtEnd
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
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
next = null;
}
}
class LinkedList {
Node head;
// Inserts a new node at the front of the list
void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
// Appends a new node at the end of the list
void append(int new_data)
{
Node new_node = new Node(new_data);
if (head == null) {
head = new_node;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
// Prints the contents of the linked list
void printList()
{
Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}
public class Main {
public static void main(String[] args)
{
LinkedList linkedList = new LinkedList();
// Insert nodes at the beginning of the linked list
linkedList.push(6);
linkedList.push(5);
linkedList.push(4);
linkedList.push(3);
linkedList.push(2);
System.out.print("Created Linked list is: ");
linkedList.printList();
// Insert 1 at the end
linkedList.append(1);
System.out.print(
"\nAfter inserting 1 at the end: ");
linkedList.printList();
}
}