日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java list翻转_JAVA实现两种方法反转单列表

發(fā)布時(shí)間:2025/3/8 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java list翻转_JAVA实现两种方法反转单列表 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

/***@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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。