想法:假如链表为1->2->3->4->5->null,然后我想的是先定义一个变量temp指针先去引用1这个节点,next每次引用temp的下一个节点,即对应是2。 然后再拿到这个链表的最后一个节点last(5),然后让head指向这个节点(5),再让这last(5)指next(2),当完成这些之后就更新head=next(即为2的节点)这个节点继续一直循环,然后到head.next==null时退出循环(上面的数字均是该节点的val值)
问题:如果 secondLast.next=null放在后面在leetcode一直显示超时,如果 secondLast.next=null;放在拿到最后一个节点的的时候却又能够通过,想知道是为什么
public static void reorderList(ListNode head) {
if(head==null||head.next==null){
return;
}
ListNode temp=head;
ListNode next=head.next;
while(temp.next.next!=null){
temp=temp.next;
}
ListNode secondLast=temp;
ListNode last=temp.next;
//secondLast.next=null;为什么要在拿到最后一个节点时,立马让倒数第二个节点指向null**_
last.next=next;
head.next=last;
secondLast.next=null;//为什么要在拿到最后一个节点时,立马让倒数第二个节点指向null**_
head=next;
reorderList(head);
}