java list翻转_JAVA实现两种方法反转单列表
/***@authorluochengcheng
* 定義一個(gè)單鏈表*/
classNode {//變量
private intrecord;//指向下一個(gè)對象
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
* 兩種方式實(shí)現(xiàn)單鏈表的反轉(zhuǎn)(遞歸、普通)
* 新手強(qiáng)烈建議旁邊拿著紙和筆跟著代碼畫圖(便于理解)*/
public classReverseSingleList {/*** 遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點(diǎn)之前先反轉(zhuǎn)后續(xù)節(jié)點(diǎn)*/
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;
}/*** 遍歷,將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針
**/
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;
}//將原鏈表的頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)置為null,再將反轉(zhuǎn)后的頭節(jié)點(diǎn)賦給head
head.setNextNode(null);
head=pre;returnhead;
}public static voidmain(String[] args) {
Node head= new Node(0);
Node tmp= null;
Node cur= null;//構(gòu)造一個(gè)長度為10的鏈表,保存頭節(jié)點(diǎn)對象head
for (int i = 1; i < 10; i++) {
tmp= newNode(i);if (1 ==i) {
head.setNextNode(tmp);
}else{
cur.setNextNode(tmp);
}
cur=tmp;
}//打印反轉(zhuǎn)前的鏈表
Node h =head;while (null !=h) {
System.out.print(h.getRecord()+ " ");
h=h.getNextNode();
}//調(diào)用反轉(zhuǎn)方法
head =reverse2(head);
System.out.println("\n**************************");//打印反轉(zhuǎn)后的結(jié)果
while (null !=head) {
System.out.print(head.getRecord()+ " ");
head=head.getNextNode();
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java list翻转_JAVA实现两种方法反转单列表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python做什么模型_主题模型初学者指
- 下一篇: iis 日志 post数据_云原生日志的