-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedLst.java
94 lines (78 loc) · 1.75 KB
/
LinkedLst.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
90
91
92
93
94
package dataStructures;
public class LinkedLst
{
static Node head;
static class Node
{
Object data;
Node next;
Node(Object data)
{
this.data=data;
}
}
static void insertFront(Object data)
{
if(head==null)
{
Node newNode = new Node(data);
head=newNode;
System.out.println("success");
return;
}
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
System.out.println("success");
}
static void insertRear(Node node, Object data) // recursive approach we can use while loop also
{
if(head==null)
{
Node newNode = new Node(data);
head=newNode;
System.out.println("success");
return;
}
if(node.next==null)
{
Node newNode = new Node(data);
node.next = newNode;
System.out.println("success");
return;
}
insertRear(node.next,data);
}
static void display()
{
Node temp = head;
if(temp==null) { System.out.println("Linked List is Empty"); return;}
while(temp.next!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
System.out.print(temp.data+" "); //residual end element similar as string problem which remains at last w/o traversing
}
static Node recursiveReverse(Node head1)
{
//Node currNode = null,prevNode = null;
if(head1==null | head1.next==null) return head1;
Node newNode = recursiveReverse(head1.next);
newNode.next.next = head1;
newNode.next = null;
return newNode;
}
public static void main(String[] args)
{
insertFront("This");
insertFront("is");
insertFront("a");
insertRear(head, "linked");
insertRear(head, "list");
display();
System.out.println();
recursiveReverse(head);
display();
}
}