LeetCode --- Partition List

题目链接

又是一个考察对链表基本操作的题目

附上代码:

复制代码
 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 class Solution {
10 public:
11     ListNode *partition(ListNode *head, int x) {
12         if (head == NULL || head->next == NULL) {
13             return head;
14         }  
15         // "P" holds the track of the linked list
16         // "pre" pointer to the previous node of "p"
17         ListNode *p = head, *pre = head, *last = head;
18         // "length" holds the length of linked list
19         int length = 0;
20         while (last->next != NULL) {
21             last = last->next;
22             length++;
23         }
24         length++;
25         while (p != NULL && length--) {
26             // if "p->val" is greater than or equal to x
27             if (p->val >= x) {
28                 ListNode *q = p;
29                 // if "q" is the first node
30                 if (q == head) {
31                     head = q->next;
32                     p = head;
33                 } else if (q == last) { // if "q" is the last node
34                     break;
35                 } else { // otherwise
36                     pre->next = q->next;
37                     p = pre->next;
38                 }
39                 // update "last"
40                 last->next = q;
41                 q->next = NULL;
42                 last = q;
43             } else {
44                 pre = p;
45                 p = p->next;
46             }
47         }
48         
49         return head;
50     }
51 };
复制代码

 

posted on   Stomach_ache  阅读(158)  评论(1编辑  收藏  举报

努力加载评论中...
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示