leetcode
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
1 package com.cn.cya.reorderlist; 2 class ListNode { 3 int val; 4 ListNode next; 5 ListNode(int x) { 6 val = x; 7 next = null; 8 } 9 } 10 public class Solution { 11 /** 12 * 1 首先将链表分成两份 13 * 2 将后面链表逆置 14 * 3 将两个链表拼起来 15 */ 16 17 public void reorderList(ListNode head) { 18 ListNode haflist=findMiddle(head); 19 20 ListNode reversehaflist=reverseList(haflist); 21 twolist(head,reversehaflist); 22 } 23 public ListNode findMiddle(ListNode head){//找到链表的中点,原理是 设置快慢指针,让快指针到底的时候,慢指针刚刚好在中间。这个应用有很多,比如找链表的第K个节点 24 if(head==null)return null; 25 ListNode fast=head; 26 ListNode slow=head; 27 while(fast!=null&&fast.next!=null){ 28 slow=slow.next; 29 fast=fast.next.next; 30 } 31 ListNode tail=slow; 32 ListNode node=slow.next; 33 tail.next=null; 34 return node; 35 36 } 37 public ListNode reverseList(ListNode list){//链表逆置 38 ListNode newHead=new ListNode(0); 39 ListNode p=null; 40 while(list!=null){ 41 p=list.next; 42 list.next=newHead.next; 43 newHead.next=list; 44 list=p; 45 } 46 return newHead.next; 47 } 48 public void twoMergeList(ListNode list1,ListNode list2){//将两个链表合并成一个链表list1,大师这个合并有问题,一直报错,在牛客网中的测试用例中一直都是25%通过,有朋友能帮我看下吗? 49 ListNode p1=list1; 50 ListNode p2=list2; 51 ListNode temp=null; 52 while(list1!=null&&list2!=null){ 53 temp=p2.next; 54 p2.next=p1.next; 55 p1.next=p2; 56 p1=p1.next.next; 57 p2=temp; 58 } 59 } 60 /** 61 * 62 * @param l1 63 * @param l2 64 * @return 65 */ 66 public static ListNode merge(ListNode l1, ListNode l2){//这个合并是我借鉴的其他朋友滴 67 ListNode cursor1=l1, cursor2=l2; 68 ListNode dummy=new ListNode(-1); 69 ListNode cursor=dummy; 70 while(cursor1!=null&&cursor2!=null){ 71 cursor.next=cursor1; 72 cursor1=cursor1.next; 73 cursor=cursor.next; 74 cursor.next=cursor2; 75 cursor2=cursor2.next; 76 cursor=cursor.next; 77 } 78 while(cursor1!=null){ 79 cursor.next=cursor1; 80 cursor1=cursor1.next; 81 cursor=cursor.next; 82 } 83 while(cursor2!=null){ 84 cursor.next=cursor2.next; 85 cursor2=cursor2.next; 86 cursor=cursor.next; 87 } 88 89 return dummy.next; 90 } 91 }