思路:
1.newHead指向翻转链表表头,currentHead指向未翻转链表头。
2.断开newHead与currentHead的连接,currentHead.next=newHead (注意:用一个临时指针tmp指向currentHead.next)
3.newHead=currentHead,currentHead=tmp
以上是一次迭代过程,注意:需要把原始链表表头head的next设置为null。
程序:
import java.util.Objects;
/**
* Created by WYS on 2018/5/14.
*/
public class ReverseLinkedList {
public static LinkedList reverseLinkedList(LinkedList node){
LinkedList newHead=node;
LinkedList currentHead=node.getNext();
newHead.setNext(null);
while(currentHead!=null){
LinkedList tmp=currentHead.getNext();
currentHead.setNext(newHead);
newHead=currentHead;
currentHead=tmp;
}
return newHead;
}
public static void main(String[] args) {
LinkedList node = new LinkedList(0);
LinkedList pNode=node;
for (int i = 1; i < 10; i++) {
pNode.setNext(new LinkedList(i));
pNode=pNode.getNext();
}
System.out.println("original LinkedList: "+node);
LinkedList reverseNode=reverseLinkedList(node);
System.out.println("Reversed LinkedList: "+reverseNode);
}
}
class LinkedList{
private int value;
private LinkedList next;
public LinkedList(int value){
next=null;
this.value=value;
}
public LinkedList getNext(){
return next;
}
public void setNext(LinkedList next){
this.next=next;
}
public int getValue(){
return value;
}
@Override
public String toString(){
String str=Objects.toString(value);
LinkedList pNode=this.next;
while(pNode !=null){
str+="->"+Objects.toString(pNode.getValue());
pNode=pNode.getNext();
}
return str;
}
}
结果:
original LinkedList: 0->1->2->3->4->5->6->7->8->9
Reversed LinkedList: 9->8->7->6->5->4->3->2->1->0