Skip to content

Instantly share code, notes, and snippets.

@ardovic
Created June 22, 2019 17:22
Show Gist options
  • Select an option

  • Save ardovic/e43b66eceb01925bc950b76d725d752f to your computer and use it in GitHub Desktop.

Select an option

Save ardovic/e43b66eceb01925bc950b76d725d752f to your computer and use it in GitHub Desktop.
Sample solution to an algorithmic problem (How to invert a single linked list?)
public class InvertSingleLinkedList {
public static void main(String[] args) {
SingleLinkedList list = new SingleLinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println("--- ORIGINAL: ---");
for (ListElement element : list) {
System.out.println("||" + element.data);
}
invertSingleLinkedList(list);
System.out.println("--- INVERTED: ---");
for (ListElement element : list) {
System.out.println("||" + element.data);
}
}
static void invertSingleLinkedList(SingleLinkedList list) {
ListElement previousElement = null;
ListElement currentElement = null;
ListElement nextElement = null;
Iterator<ListElement> iterator = list.iterator();
while (iterator.hasNext()) {
if (previousElement == null) {
previousElement = iterator.next();
} else if (currentElement == null) {
currentElement = iterator.next();
previousElement.next = null;
} else {
nextElement = iterator.next();
currentElement.next = previousElement;
previousElement = currentElement;
currentElement = nextElement;
}
}
if (currentElement != null) {
currentElement.next = previousElement;
list.head = currentElement;
}
}
static class ListElement {
ListElement next;
int data;
}
static class SingleLinkedList implements Iterable<ListElement> {
ListElement head;
void add(int data) {
ListElement element = new ListElement();
element.data = data;
if (head == null) {
head = element;
} else {
element.next = head;
head = element;
}
}
@Override
public Iterator<ListElement> iterator() {
return new Iterator<>() {
ListElement currentElement = head;
@Override
public boolean hasNext() {
return currentElement != null;
}
@Override
public ListElement next() {
ListElement temp = currentElement;
currentElement = currentElement.next;
return temp;
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment