-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSinglyLinkedListImpl.java
More file actions
101 lines (85 loc) · 1.86 KB
/
Copy pathSinglyLinkedListImpl.java
File metadata and controls
101 lines (85 loc) · 1.86 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
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
95
96
97
98
99
100
101
package com.sky.pgm;
@SuppressWarnings("rawtypes")
public class SinglyLinkedListImpl<T> {
private Node head;
@SuppressWarnings("unchecked")
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
System.out.println("Adding: "+element);
Node<T> tmp = head;
while(true){
if(tmp==null){
head = nd;
break;
} else if(tmp.getNextref() == null) {
tmp.setNextref(nd);
break;
} else{
tmp = tmp.getNextref();
}
}
}
@SuppressWarnings("unchecked")
public void traverse(){
Node<T> tmp = head;
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue()+"\t");
tmp = tmp.getNextref();
}
}
@SuppressWarnings("unchecked")
public void reverse(){
System.out.println("Reversing the linkedlist");
Node<T> prev = null;
Node<T> current = head;
Node<T> next = null;
while(current!=null){
next = current.getNextref();
current.setNextref(prev);
prev = current;
current = next;
}
head = prev;
}
public static void main(String[] args) {
SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<>();
sl.add(3);
sl.add(32);
sl.add(54);
sl.add(89);
System.out.println();
sl.traverse();
System.out.println();
sl.reverse();
sl.traverse();
}
}
class Node<T> implements Comparable<T> {
private T value;
private Node<T> nextref;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextref() {
return nextref;
}
public void setNextref(Node<T> nextref) {
this.nextref = nextref;
}
@Override
public int compareTo(T arg0) {
System.out.println("CompareTo called");
if(arg0 == this.value){
return 0;
}
else
return 1;
}
}