1
1
package linkedlists ;
2
2
3
- import java .util .LinkedList ;
4
-
5
3
/**
6
4
* Given the pointer/reference to the head of a singly linked list,
7
5
* reverse it and return the pointer/reference to the head of reversed linked list.
@@ -16,29 +14,57 @@ static class Node{
16
14
public int data ;
17
15
public Node next ;
18
16
19
- Node (int a , Node next ){
17
+ Node (int a ){
20
18
this .data = a ;
21
- this .next = next ;
19
+ this .next = null ;
22
20
}
23
21
}
24
22
23
+ static void printList (Node node ) {
24
+ while (node != null ) {
25
+ System .out .print (node .data + " " );
26
+ node = node .next ;
27
+ }
28
+ }
29
+
25
30
public static void main (String args []){
26
31
27
- LinkedList < Integer > list1 = new LinkedList <> ();
28
- list1 .add (7 );
29
- list1 .add (14 );
30
- list1 .add (21 );
31
- list1 .add (28 );
32
+ SinglyLinkedList list1 = new SinglyLinkedList ();
33
+ list1 .head = new Node (7 );
34
+ list1 .head . next = new Node (14 );
35
+ list1 .head . next . next = new Node (21 );
36
+ list1 .head . next . next . next = new Node (28 );
32
37
33
- System .out .println (list1 );
34
- reverse_list (list1 );
38
+ printList (head );
35
39
40
+ reverse_list (head );
41
+
42
+ printList (reverse_list (head ));
36
43
}
37
-
38
-
39
44
40
- private static void reverse_list (LinkedList <Integer > list1 ) {
41
- // TODO Auto-generated method stub
45
+ private static Node reverse_list (Node head2 ) {
46
+
47
+ if (head2 ==null ||head2 .next ==null ){
48
+ return null ;
49
+ }
50
+
51
+ Node start = head2 ;
52
+ Node point = head2 .next ;
53
+
54
+ start .next = null ;
55
+
56
+ while (point != null ){
57
+ Node temp = point .next ;
58
+ System .out .println ("test2" );
59
+ point .next = start ;
60
+
61
+ point = temp ;
62
+
63
+ }
64
+
65
+ head2 = start ;
66
+ return head2 ;
67
+
42
68
43
69
}
44
70
}
0 commit comments