86. 分隔链表

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 //直接模拟,建立两个虚拟节点就可以了
10 class Solution 
11 {
12 public:
13     ListNode* partition(ListNode* head, int x) 
14     {
15         ListNode* dummy1 = new ListNode(-1);
16         ListNode* dummy2 = new ListNode(-1);
17 
18         ListNode* pre1 = dummy1;
19         ListNode* pre2 = dummy2;
20 
21         while(head)
22         {
23             if(head->val < x)
24             {
25                 pre1->next = head;
26                 head = head->next;
27                 pre1 = pre1->next;
28             }
29             else
30             {
31                 pre2->next = head;
32                 head = head->next;
33                 pre2 = pre2->next;
34             }
35         }
36         pre1->next = dummy2->next;
37         pre2->next = NULL;
38 
39         return dummy1->next;
40     }
41 };

 

posted @ 2020-03-31 11:09  Jinxiaobo0509  阅读(77)  评论(0)    收藏  举报