Java转置_Java实现单链表的逆转置
單鏈表逆轉(zhuǎn)置的遞歸與非遞歸方式
package link.reverse;
// 定義一個(gè)單鏈表
class Node {
//變量
private int record;
//指向下一個(gè)對象
private Node nextNode;
public Node(int record) {
this.record = record;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
/**
* 兩種方式實(shí)現(xiàn)單鏈表的反轉(zhuǎn)(遞歸、普通)
*/
public class RevSingleLinkFactory {
/**
* 遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點(diǎn)之前先反轉(zhuǎn)后續(xù)節(jié)點(diǎn)
*/
//最終傳遞一個(gè)指向最后一個(gè)節(jié)點(diǎn)的變量
public static Node reverse1(Node head) {
//當(dāng)為空或者本節(jié)點(diǎn)為末尾節(jié)點(diǎn)的時(shí)候
if (head ==null ||head.getNextNode()==null)
return head;
Node reversedHead = reverse1(head.getNextNode());
//獲取先前的下一個(gè)節(jié)點(diǎn),讓該節(jié)點(diǎn)指向自身
head.getNextNode().setNextNode(head);
//破壞以前自己指向下一個(gè)節(jié)點(diǎn)
head.setNextNode(null);
//層層傳遞給最上面的
return reversedHead;
}
/**
* 遍歷,將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針
*/
public static Node reverse2(Node head) {
if (null == head) {
return head;
}
Node pre = head;
Node cur = head.getNextNode();
Node next;
while (cur !=null) {
//斷之前先找到原始的下一個(gè)節(jié)點(diǎn)
next = cur.getNextNode();
//逆序連接
cur.setNextNode(pre);
//兩個(gè)節(jié)點(diǎn)同時(shí)滑動(dòng)
pre = cur;
cur = next;
}
//將原鏈表的頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)置為null,再將反轉(zhuǎn)后的頭節(jié)點(diǎn)賦給head
head.setNextNode(null);
head = pre;
return head;
}
public static void main(String[] args) {
//帶有頭結(jié)點(diǎn)
Node head = new Node(0);
Node tmp = null; // 保存臨時(shí)變量
Node cur = null; // 始終指向末尾節(jié)點(diǎn)
//構(gòu)造一個(gè)長度為10的鏈表,保存頭節(jié)點(diǎn)對象head
//利用尾插入法
for (int i = 1; i < 10; i++) {
tmp = new Node(i);
if (1 == i) {
head.setNextNode(tmp);
} else {
cur.setNextNode(tmp);
}
cur = tmp;
}
//打印反轉(zhuǎn)前的鏈表
Node h = head;
while (h !=null) {
System.out.print(h.getRecord() + " ");
h = h.getNextNode();
}
//調(diào)用反轉(zhuǎn)方法
head = reverse1(head);
System.out.println("\n*******************");
//打印反轉(zhuǎn)后的結(jié)果
while (head !=null) {
System.out.print(head.getRecord() + " ");
head = head.getNextNode();
}
}
}
總結(jié)
以上是生活随笔為你收集整理的Java转置_Java实现单链表的逆转置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用u盘更新电脑系统出现黑屏怎么办 u盘更
- 下一篇: java web 集成dom4j_[Ja