letcode刷题
改变链表的位置
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
这是自己最开始的想法,写的不够简洁。
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) {
return;
}
ListNode nHead = new ListNode(0);
ListNode cur = head;
int i = 0;
ListNode dump = nHead;
while (cur != null) {
if (i == 0) {
ListNode iNode = cur;
cur = cur.next;
dump.next = iNode;
iNode.next = null;
dump = dump.next;
i = 1;
} else {
ListNode lastNode = lastNode(cur);
if (lastNode == cur) {
dump.next = lastNode;
break;
} else {
ListNode preLastNode = nodeBeforeLast(cur, lastNode);
preLastNode.next = null;
dump.next = lastNode;
dump = dump.next;
i = 0;
}
}
}
head = nHead.next;
}
public ListNode lastNode(ListNode head) {
if (head == null) {
return null;
}
while (head.next != null) {
head = head.next;
}
return head;
}
public ListNode nodeBeforeLast(ListNode head, ListNode last) {
while (head.next != last) {
head = head.next;
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution();
solution.reorderList(head);
}
}
再看了别人写的,感觉真的是几行代码的问题,然后自己就写了那么多行.如果有倒数第二个结点,就先找到倒数第二结点,倒数第二结点指向空,倒数第一个结点指向此时头结点的下一个结点,头节的下一个结点变成倒数第一个结点。然后头结点指向下下一个结点。
public class Solution {
public void reorderList(ListNode head) {
ListNode rear=head;
ListNode tmp;
while(head!=null&&head.next!=null){
while(rear.next.next!=null){
rear=rear.next;
}
tmp=rear.next;
rear.next=null;
tmp.next=head.next;
head.next=tmp;
head=rear=tmp.next;
}
}
}