日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/8 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java list翻转_JAVA实现两种方法反转单列表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

/***@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();

}

}

}

總結

以上是生活随笔為你收集整理的java list翻转_JAVA实现两种方法反转单列表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。