题目很简单,把12345重新排序成15243.
方法是把愿链表打进栈里,同时记录下节点的个数
之后从栈中弹出一个插入原链表中。
public static void reorderList(ListNode head) {
if (head!=null) {
Stack<ListNode> s = new Stack<ListNode>();
int num = 0;
ListNode h = head;
ListNode p = head;
while (true) {
s.push(p);
num++;
if (p.next != null) {
p = p.next;
} else break;
}
int num2=num;
int jo=num%2;
num = num / 2;
if(jo==0)num=num--;
ListNode t=null;
for (int i = 0; i < num; i++) {
t = s.pop();
t.next = h.next;
h.next = t;
h = t.next;
}
//if(jo==0) t.next=null;
p=head;
for (int i = 0; i <num2-1; i++) {
p = p.next;
}
p.next=null;
//for testing
p=head;
for (int i = 0; i <6; i++) {
System.out.println(p.val);
if (p.next != null) {
p = p.next;
} else break;
}
}
}Update:2015/08/15
这道题上面的解法不是很好,因为用到了额外的栈,而原题是要求使用in place,所以不应该使用栈。更好的解法是分三步,第一步找到中间节点(快慢指针),第二步是反转下半段,第三部是将前半段和反转后的后半段进行merge。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: void
*/
public void reorderList(ListNode head) {
// write your code here
if (head != null && head.next != null) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode second = slow.next;
slow.next = null;
if (second != null && second.next != null) {
ListNode pre = second;
ListNode curr = second.next;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
second.next = null;
second = pre;
}
ListNode p1 = head;
ListNode p2 = second;
while (p2 != null) {
ListNode tmp = p2.next;
p2.next = p1.next;
p1.next = p2;
p1 = p1.next.next;
p2 = tmp;
}
}
}
}
本文介绍了链表重新排序的问题,原始解决方案使用了栈来辅助排序。为了改进效率,提出了直接在链表内部操作的方法,避免了额外的空间使用。通过快慢指针找到链表中点,反转后半部分链表,然后合并前半部分和反转后的后半部分链表,实现了更高效且就地操作的链表排序。
5万+

被折叠的 条评论
为什么被折叠?



