1 class Solution:
 2     def constructLink(self,lists):
 3         n = len(lists)
 4         if n == 0:
 5             return None
 6         if n == 1:
 7             return ListNode(lists[0])
 8         
 9         head = ListNode(lists[-1])
10         for i in range(n-2,-1,-1):
11             cur = ListNode(lists[i])
12             cur.next = head 
13             head = cur
14         return head
15     
16     def partition(self, head: ListNode, x: int) -> ListNode:
17         lists = []
18         while head != None:
19             lists.append(head.val)
20             head = head.next
21         before = []
22         after = []
23         for i in range(len(lists)):
24             if lists[i] < x:
25                 before.append(lists[i])
26             else:
27                 after.append(lists[i])
28         return self.constructLink(before + after)

将链表中的节点,按照x值分别存储到两个集合中,再用重新拼接的集合建立链表。

posted on 2019-12-10 19:48  Sempron2800+  阅读(143)  评论(0编辑  收藏  举报