-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSLL.java
More file actions
45 lines (35 loc) · 980 Bytes
/
SLL.java
File metadata and controls
45 lines (35 loc) · 980 Bytes
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
package com.ub.interview;
public class SLL<E> {
public Node<E> head = null;
public void addPayload(E aPayload) {
head = new Node<E>(aPayload, head);
}
@Override
public String toString() {
Node<E> tempHead = head;
String result = "";
while(tempHead != null) {
result += tempHead.getPayload();
if(tempHead.next!= null) {
tempHead = tempHead.next;
result += " ==> ";
}
else {
break;
}
}
return result;
}
public Node<E> reverseList(Node<E> currentNode,Node<E> toBeNextNode) {
Node<E> curHead = currentNode;
if((curHead == null || curHead.getNext() == null) && toBeNextNode == null) {
return curHead; //ignore size 0 & 1
}
if (curHead.getNext() != null) {
curHead = reverseList(currentNode.getNext(), currentNode); // travarse till end recursively
}
currentNode.next = toBeNextNode; // reverse link
toBeNextNode.next = null;
return curHead;
}
}