- 在有關(guān)鏈表的題目中,最需要注意的地方就是各個結(jié)點引用的調(diào)整,否則很容易因為混亂的指向?qū)е滤姥h(huán)等情況。
- 技巧:定義引用指向(保存)某個結(jié)點,防止由于調(diào)整鏈表結(jié)構(gòu),導(dǎo)致某些結(jié)點丟失。
- 對于翻轉(zhuǎn)單鏈表一般有兩種做法:
- 1、逐個翻轉(zhuǎn),保存當(dāng)前結(jié)點的前一個結(jié)點,然后調(diào)整指向。
- 2、不斷的將后面的鏈表丟到頭節(jié)點的后面,然后將頭節(jié)點丟到最后面。
方法一:
/**
* 方法一:逐個翻轉(zhuǎn)
* @param head
* @return
*/
public static ListNode reverse(ListNode head) {
if (head == null)
return null;
ListNode pre = null;
ListNode cur = head;
while (cur != null)
{
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
方法二:
//方法二:不斷選擇后一個結(jié)點,插入到頭節(jié)點后面
public static ListNode re(ListNode head) {
if (head == null) return null;
if (head.next == null)
return head;
if (head.next.next == null){
ListNode n = head.next;
head.next = null;
n.next = head;
return n;
}
ListNode cur = head.next.next;
ListNode pre = head.next;
while (cur != null){
//臨時結(jié)點,存放當(dāng)前結(jié)點的下一個結(jié)點
ListNode temp = cur.next;
//將cur的前一個結(jié)點指向cur的下一個結(jié)點
pre.next = temp;
//解除cur.next的先前指向,重定向為head下一個結(jié)點。
cur.next = head.next;
//解除head的先前指向,重定向為cur
head.next = cur;
//調(diào)整引用,cur向后一位
cur = temp;
}
//添加引用到頭節(jié)點的下一個結(jié)點,即翻轉(zhuǎn)鏈表后的新頭結(jié)點。
ListNode newNode = head.next;
//移動頭節(jié)點到尾部
pre.next = head;
//解除下一個指向的引用,避免死循環(huán)
head.next = null;
return newNode;
}
https://github.com/yuanoOo/Algorithm/tree/master/Linked%20List