leetcode 鍊錶 排序

2021-07-25 08:24:16 字數 799 閱讀 9174

思路:使用歸併排序。拆分、合併均採用遞迴方式。

public listnode sortlist(listnode head) 

pre.next = null;

return merge(sortlist(head), sortlist(slow));

}public listnode merge(listnode l1, listnode l2) else

}

思路:新建乙個頭指標,直接插入排序

public listnode insertionsortlist(listnode head) else

low.next = pre;

temp.next = pre.next;

pre.next = fast;

pre = temp.next;}}

return newhead.next;

}

思路:將鍊錶後半段翻轉,前半段、後半段交替輸出

public void reorderlist(listnode head) 

p = r.next;

while(p.next != null)

listnode s,t;

t = r.next;

r.next = null;

s = head;

while(s != null && s.next != null)

s.next = t;

}

leetcode 鍊錶排序

對鍊錶排序,用歸併排序。題目要求空間時間複雜度為o nlogn 但是空間複雜度為o 1 1.自己寫的程式,時間複雜度為o nlogn 但是空間複雜度為o n 用快慢指標 分別走2步和1步 找到中間節點。但是最後排序的部分,用複製將排好序的部分貼上會原來鍊錶中,這個方法比較笨,而且增加空間複雜度,並不...

leetcode 排序鍊錶

利用歸併排序的思想,不過這裡排序的不是列表,是乙個鍊錶。具體 如下 definition for singly linked list.class listnode object def init self,x self.val x self.next none class solution obj...

LeetCode 排序鍊錶

給你鍊錶的頭結點head,請將其按公升序排列並返回排序後的鍊錶。高階 示例 1 輸入 head 4,2,1,3 輸出 1,2,3,4 示例 2 輸入 head 1,5,3,4,0 輸出 1,0,3,4,5 示例 3 輸入 head 輸出 歸併排序 將鍊錶拆分為二 listnode head1 sor...