[英]Reversing a singly linked list iteratively
必須為O(n)並就地(空間復雜度為1)。 下面的代碼可以工作,但是有沒有更簡單或更完善的方法?
public void invert() {
if (this.getHead() == null)
return;
if (this.getHead().getNext() == null)
return;
//this method should reverse the order of this linked list in O(n) time
Node<E> prevNode = this.getHead().getNext();
Node<E> nextNode = this.getHead().getNext().getNext();
prevNode.setNext(this.getHead());
this.getHead().setNext(nextNode);
nextNode = nextNode.getNext();
while (this.getHead().getNext() != null)
{
this.getHead().getNext().setNext(prevNode);
prevNode = this.getHead().getNext();
this.getHead().setNext(nextNode);
if (nextNode != null)
nextNode = nextNode.getNext();
}
this.head = prevNode;
}
編輯以刪除每次迭代的額外比較:
public void invert() {
Node<E> prev = null, next = null;;
if (head == null) return;
while (true) {
next = head.getNext();
head.setNext(prev);
prev = head;
if (next == null) return;
head = next;
}
}
與LinkedList的此實現一起使用: https : //stackoverflow.com/a/25311/234307
public void reverse() {
Link previous = first;
Link currentLink = first.nextLink;
first.nextLink = null;
while(currentLink != null) {
Link realNextLink = currentLink.nextLink;
currentLink.nextLink = previous;
previous = currentLink;
first = currentLink;
currentLink = realNextLink;
}
}
這個怎么樣:
public void invert() {
if (head != null) {
for (Node<E> tail = head.getNext(); tail != null; ) {
Node<E> nextTail = tail.getNext();
tail.setNext(head);
head = tail;
tail = nextTail;
}
}
}
使用一個獨立的實現,即List由頭Node表示:
public class Node<E>
{
Node<E> next;
E value;
public Node(E value, Node<E> next)
{
this.value = value;
this.next = next;
}
public Node<E> reverse()
{
Node<E> head = null;
Node<E> current = this;
while (current != null) {
Node<E> save = current;
current = current.next;
save.next = head;
head = save;
}
return head;
}
}
public void reverse(){
Node middle = head;
Node last = head;
Node first = null;
while(last != null){
middle = last;
last = last.next;
middle.next = first;
first = middle;
}
head = middle;
}
public void invert() {
if (first == null) return;
Node<E> prev = null;
for ( Node<E> next = first.next; next != null; next = first.next) {
first.next = prev;
prev = first;
first = next;
}
first.next = prev;
}
修改節點類
您可以覆蓋Node類中的toString方法以輸入任何數據
public class Node { public Node node; private int data; Node(int data) { this.data = data; } @Override public String toString() { return this.data+""; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.