/***@authorluochengcheng
* 定義一個單鏈表*/
classNode {//變量
private intrecord;//指向下一個對象
privateNode nextNode;public Node(intrecord) {super();this.record =record;
}public intgetRecord() {returnrecord;
}public void setRecord(intrecord) {this.record =record;
}publicNode getNextNode() {returnnextNode;
}public voidsetNextNode(Node nextNode) {this.nextNode =nextNode;
}
}/***@authorluochengcheng
* 兩種方式實現單鏈表的反轉(遞歸、普通)
* 新手強烈建議旁邊拿著紙和筆跟著代碼畫圖(便于理解)*/
public classReverseSingleList {/*** 遞歸,在反轉當前節點之前先反轉后續節點*/
public staticNode reverse(Node head) {if (null == head || null ==head.getNextNode()) {returnhead;
}
Node reversedHead=reverse(head.getNextNode());
head.getNextNode().setNextNode(head);
head.setNextNode(null);returnreversedHead;
}/*** 遍歷,將當前節點的下一個節點緩存后更改當前節點指針
**/
public staticNode reverse2(Node head) {if (null ==head) {returnhead;
}
Node pre=head;
Node cur=head.getNextNode();
Node next;while (null !=cur) {
next=cur.getNextNode();
cur.setNextNode(pre);
pre=cur;
cur=next;
}//將原鏈表的頭節點的下一個節點置為null,再將反轉后的頭節點賦給head
head.setNextNode(null);
head=pre;returnhead;
}public static voidmain(String[] args) {
Node head= new Node(0);
Node tmp= null;
Node cur= null;//構造一個長度為10的鏈表,保存頭節點對象head
for (int i = 1; i < 10; i++) {
tmp= newNode(i);if (1 ==i) {
head.setNextNode(tmp);
}else{
cur.setNextNode(tmp);
}
cur=tmp;
}//打印反轉前的鏈表
Node h =head;while (null !=h) {
System.out.print(h.getRecord()+ " ");
h=h.getNextNode();
}//調用反轉方法
head =reverse2(head);
System.out.println("\n**************************");//打印反轉后的結果
while (null !=head) {
System.out.print(head.getRecord()+ " ");
head=head.getNextNode();
}
}
}