-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathReverselinkedlist.java
More file actions
67 lines (56 loc) · 1.47 KB
/
Reverselinkedlist.java
File metadata and controls
67 lines (56 loc) · 1.47 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
package Linkedlist;
public class Reverselinkedlist {
Node head;
static class Node{
String data;
Node next;
Node(String data)
{
this.data=data;
this.next=null;
}
}
public Node reverse(Node head)
{
Node current_node=head;
Node prevnode=null;
while(current_node!=null)
{Node tempnode=current_node.next;
current_node.next=prevnode;
prevnode=current_node;
current_node=tempnode;
}
return prevnode;
}
/*
RECURSIVE METHOD:-
public Node reverse(Node head)
{
if(head==null||head.next==null)
{return head;}
Node new_head=reverse(head.next);
Node headnext=head.next;
headnext.next=head;
head.next=null;
return new_head;
}*/
public void printlist(Node head)
{
Node current_node=head;
while(current_node!=null)
{
System.out.println(current_node.data);
current_node=current_node.next;
}
}
public static void main(String args[])
{
Reverselinkedlist ll=new Reverselinkedlist();
ll.head = new Node("85");
ll.head.next = new Node("15");
ll.head.next.next = new Node("4");
ll.head.next.next.next = new Node("2");
Node t=ll.reverse(ll.head);
ll.printlist(t);
}
}