-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample18.java
64 lines (42 loc) · 1.47 KB
/
Example18.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
package applications.algorithms;
import datastructs.adt.SingleLinkedList;
/** Category: Algorithms
* ID: Example 18
* Description: Reverse single linked list in place
* Taken From:
* Details:
* TODO
*/
public class Example18 {
public static void reverse(SingleLinkedList<Integer> list){
int middle = list.size() >> 1;
for(int i=0; i<middle; ++i){
SingleLinkedList<Integer>.Node node1 = list.get(i);
SingleLinkedList<Integer>.Node node2 = list.get(list.size() - i -1);
// we want to swap the data held by these two nodes
Integer tmp = node1.getData();
node1.setData(node2.getData());
node2.setData(tmp);
}
}
public static void main(String[] args){
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
for (int i = 0; i < 10; i++) {
linkedList.pushFront(i);
}
System.out.println("List before reversing...\n");
linkedList.print();
Example18.reverse(linkedList);
System.out.println("\nList after reversing...\n");
linkedList.print();
linkedList = new SingleLinkedList<>();
for (int i = 0; i < 11; i++) {
linkedList.pushFront(i);
}
System.out.println("List before reversing...\n");
linkedList.print();
Example18.reverse(linkedList);
System.out.println("\nList after reversing...\n");
linkedList.print();
}
}