題目是力扣的重組鏈表 鏈接:https://leetcode-cn.com/problems/reorder-list/
代碼
public ListNode sumIsN(ListNode head){
if(head == null) return head;
if(head.next == null) return head;
// 鏈表的臨時變數 頭 尾前 尾 新鏈表的鏈尾 暫存頭部指標
ListNode front,nextTail,tail,newtail,nextHead;
front = newtail = head; // 指標初始化
nextTail = tail = null; // 初始化
do{
nextTail = front; // tail的初定位
nextHead = front.next; // 下次的head
// 1. 遍歷當前鏈表 尋找 尾前和鏈尾
while(nextTail.next.next != null) nextTail = nextTail.next;
tail = nextTail.next;
// 2。新鏈表連頭 頭尾相連 當前鏈尾設定next為null
newtail.next = front;
front.next = tail;
nextTail.next = null;
// 3. 更新front 和 newtail
newtail = tail;
front = nextHead;
}while(nextHead!=nextTail && nextHead.next!=nextTail);
// 總個數為奇數 頭尾指標相等
// 偶數 頭尾相連
// 最后一次的連接
newtail.next = front;
return head;
}
當遇到1 -> 2的輸入的時候報錯了 java.lang.NullPointerException
指向的是 while(nextTail.next.next != null) nextTail = nextTail.next;
debug 發現剛進入dowhile 的時候 nextTail.next.next為空了
但是不知道怎么修改... 新人求教
uj5u.com熱心網友回復:
給你個sample參考吧public class Sample {
static class ListNode {
ListNode next;
int value;
public ListNode() {}
public ListNode(int value) {this.value=https://bbs.csdn.net/topics/value;}
public void print() {
System.out.printf("%d", value);
ListNode node = this.next;
while(node!=null) {
System.out.printf("->%d", node.value);
node = node.next;
}
}
}
public static ListNode reorderList(ListNode head){
if(head == null) return head;
if(head.next == null) return head;
ListNode node = head;
ListNode pre = head;
ListNode next = pre.next;
do {
while(next!=null && next.next!=null) { // 查找最后一個節點和倒數第二個節點
pre = pre.next;
next = next.next;
}
if (next != null) { //如果能找到最后一個節點
next.next = node.next; //把最后一個節點的next指向當前node節點的next節點
node.next = next; //然后當前node節點的next只想最后一個節點(相當于把最后一個節點插入node和node.next之間)
pre.next = null; //然后修改倒數第二個節點為最后一個節點
node = next.next; //然后修改當node前節點為之前的node.next節點
} else {
break;
}
pre = node; //重續修改pre和next,繼續下一次回圈
next = pre.next;
} while(node!=null && node.next!= null);
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node = head;
for (int i=1; i<5; i++) {
node.next = new ListNode(i+1);
node = node.next;
}
head.print();
System.out.println();
head = reorderList(head);
head.print();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/184800.html
標籤:Java相關
上一篇:關于mq訊息丟失,沒有思路了。
