## Posted By

edwarddr on 05/21/12

# reverse a single linked list

/ Published in: Java

It's sample code of reversing a linked list with either recursive or non-recursive.

2. {
4.
6. {
8. }
9.
10.
11.
12. public void reverse_all()
13. {
15. return;
16.
18. }
19.
20. // 1, 2, 3
21. private Node reverse(Node n)
22. {
24. if (n._next == null) return head;
25.
26. Node nextNode = n._next;
27. n._next = null;
28. nextNode = reverse(nextNode);
29. nextNode._next = n;
30. return n;
31. }
32.
33. // using non-recursion
34. private void reverse_nc(Node n)
35. {
36. Node p = null;
37. Node q = null;
38.
39. while (n != null){
40. p = n._next;
41. n._next = q;
42. q = n;
43. n = p;
44.
45. }
47. }
48.
49.
50. void printV()
51. {
53. while(cur!=null)
54. {
55. System.out.print(cur._value + " ");
56. cur = cur._next;
57. }
58. System.out.println(", End!");
59. }
60.
61. public static void main(String args[])
62. {
64. Node n1 = new Node(1);
65. Node n2 = new Node(2);
66. Node n3 = new Node(3);
67. n1._next = n2;
68. n2._next = n3;
70.
71. list.printV();
72. list.reverse_all();
73. list.printV();
74. }
75. }
76. class Node
77. {
78. int _value;
79. Node _next;
80.
81. Node( int value)
82. {
83. _value = value;
84. _next = null;
85. }
86. }