Created
March 6, 2019 12:10
-
-
Save abbath0767/7c9a2b3ff15eacfd5bc28b28a957cf28 to your computer and use it in GitHub Desktop.
Reversed SingleLinkedList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
SingleLinkList<Integer> list = new SingleLinkList<>(); | |
Random rand = new Random(); | |
for (int i = 0; i < 10; i++) { | |
list.add(rand.nextInt(100)); | |
} | |
System.out.println("List data: " + list.toString() + " with size: " + list.size()); | |
list.reverse(); | |
System.out.println("Reversed list: " + list.toString() + " with size: " + list.size()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SingleLinkList<T> { | |
private Node head; | |
private class Node { | |
T data; | |
Node next; | |
private Node(T data) { | |
this.data = data; | |
} | |
@Override | |
public String toString() { | |
return data + " "; | |
} | |
} | |
public int size() { | |
int size = 0; | |
if (head == null) | |
return size; | |
size = 1; | |
Node current = head; | |
while (true) { | |
if (current.next != null) { | |
size++; | |
current = current.next; | |
} else { | |
break; | |
} | |
} | |
return size; | |
} | |
public void add(T element) { | |
if (element == null) | |
return; | |
Node newNode = new Node(element); | |
if (head == null) { | |
head = newNode; | |
return; | |
} | |
Node current = head; | |
while (true) { | |
if (current.next == null) { | |
current.next = newNode; | |
break; | |
} else { | |
current = current.next; | |
} | |
} | |
} | |
@Override | |
public String toString() { | |
StringBuilder result = new StringBuilder(); | |
result.append("Array: ["); | |
Node current = head; | |
if (current == null) { | |
result.append("]"); | |
return result.toString(); | |
} | |
while (true) { | |
result.append(current.data); | |
current = current.next; | |
if (current == null) { | |
result.append("]"); | |
return result.toString(); | |
} else { | |
result.append(" "); | |
} | |
} | |
} | |
public void reverse() { | |
Node current = head; | |
Node prev = null, next = null; | |
while (current != null) { | |
next = current.next; | |
current.next = prev; | |
prev = current; | |
current = next; | |
} | |
head = prev; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment