最开始的想法:假如链表为1->2->3->4->5->null,然后我想的是先定义一个变量temp指针先去引用1这个节点,tempRight每次引用temp的下一个节点,即对应是2。 然后再拿到这个链表的最后一个节点lastNode(5),然后让temp指向这个节点(5),再让这lastNode(5)指向tempRight(2),当完成这些之后就更新temp=tempRight(即为2的节点)这个节点继续一直循环,然后到temp.next==null时退出循环(上面的数字均是该节点的val值)
代码如下:
public static ListNode reorderList(ListNode head) { //假设开始前1->2->3->4->5->null if (head == null || head.next == null) return head; ListNode temp = head; while (temp.next != null) { ListNode next = temp.next.next;//提前将next指向下一次递归所要传递的节点,即为“3”; ListNode lastNode = modify(temp);//获取最后一个节点,并且将倒数第二个节点指向null ListNode tempRight=temp.next;//Right代表temp后面的一个节点 temp.next = lastNode;//先将temp节点指向最后一个节点 lastNode.next =tempRight; //虽然可以让最后一个节点指向第三个节点"2",但是链表的倒数第二个节点依然指向了最后一个节点,所以得让倒数第二个节点指向null temp = next; } return head; } //递归获取最后一个节点 public static ListNode lastNode(ListNode head){ //比如链表为1->2->3->4->5->null //int flag=0; //空指针会异常 //if(head.next.next==null)//相当于在倒数第二个节点即在4这个节点时,让4->null //flag=1;//标记倒数第二个节点 if (head == null || head.next == null){ return head; } //if(flag==1) // head.next=null; return lastNode(head.next); } //返回最后一个节点并将倒数第二个节点置为null public static ListNode modify(ListNode head){ ListNode temp=head; ListNode last=lastNode(head); while (temp!=null){ if(temp.next.next==null){ temp=null;//将所谓倒数第二个节点指向null break; } temp=temp.next; } return last;//返回最后一个节点 } public static void ListNodetoString(ListNode node){ while (node!=null){ System.out.print(node.val+" "); node=node.next; } } public static void main(String[] args) { ListNode list1=new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,null)))); ListNode list2=new ListNode(1,new ListNode(3,new ListNode(4,null))); ListNodetoString(reorderList(list1)); }