标签:链表 after int 指针 新建 遍历 else 空间 str
public ListNode partition(ListNode head, int x) {
ListNode beforeHead = new ListNode(-1);
ListNode afterHead = new ListNode(-1);
ListNode before = beforeHead;
ListNode after = afterHead;
while (head != null){
if(head.val < x){
before.next = head;
before = before.next;
}else {
after.next = head;
after = after.next;
}
head = head.next;
}
after.next = null;
before.next = afterHead.next;
return beforeHead.next;
}
时间复杂度:O(N),N为链表长度
空间复杂度:O(1),这个版本的代码是没有分配新空间的版本,只移动了原有的结点,因此没有使用任何额外空间。
另外,after.next = null是很有必要的,不能出现野指针
我自己写的答案是新建了结点的
public ListNode partition(ListNode head, int x) {
ListNode beforeHead = new ListNode(-1);
ListNode afterHead = new ListNode(-1);
ListNode before = beforeHead;
ListNode after = afterHead;
while (head != null){
if(head.val < x){
before.next = new ListNode(head.val);
before = before.next;
}else {
after.next = new ListNode(head.val);
after = after.next;
}
head = head.next;
}
after.next = null;
before.next = afterHead.next;
return beforeHead.next;
}
标签:链表 after int 指针 新建 遍历 else 空间 str
原文地址:https://www.cnblogs.com/swifthao/p/13045524.html