码迷,mamicode.com
首页 > 其他好文 > 详细

086. Partition List

时间:2018-11-10 15:13:21      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:def   you   nal   过程   ptr   大于   lan   get   input   

题目链接:https://leetcode.com/problems/partition-list/description/

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

 

思路:

  • 根据题目所述,要求将链表中小于x(< x )的结点放在链表的左侧,大于等于x(>= x)的结点放置在链表的右侧;并且要求元素的相对顺序保持不变。
  • 最直观的想法就是遍历链表,将元素中大于等于x(>= x)的结点拎出来,组成一个新的链表;当对原始链表遍历完成后,将拎出来的新链表插入到处理后的原始链表的后面即可。

  注意:上面描述的是将大于等于x(>= x)的结点拎出来,也可将小于x(< x)的结点拎出来,两者处理过程基本一样。只是组合成所求链表时插入位置不同。

 

编码如下

 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 == nullptr) return head;       // 链表为空,则直接返回
13         
14         // 操作原始链表的准备工作
15         // 包括创建一个辅助结点指向链表的头结点
16         ListNode *pHead = new ListNode(-1);
17         pHead->next = head;
18         ListNode *pre = pHead;      // pre指向遍历到的结点的前驱结点
19         ListNode *cur = head;       // cur指向遍历到的当前结点(即待处理结点)
20         
21         // 创建指向大于等于x(>= x ) 结点的链表
22         // 用pNew指针指向该链表的头结点,pNew为辅助结点
23         ListNode *pNew = new ListNode(-1);
24         ListNode *ptrNew = pNew;
25         
26         // 对原始链表进行遍历
27         while (cur != nullptr)
28         {
29             if (cur->val >= x)    // 将原始链表中大于等于x(>= x)的结点分离出来,形成新的链表
30             {
31                 ListNode *pTemp = cur;
32                 pre->next = pTemp->next;
33                 cur = cur->next;
34                 
35                 ptrNew->next = pTemp;
36                 ptrNew = ptrNew->next;
37                 ptrNew->next = nullptr;
38             }
39             else    // 对于原始链表中小于x(< x)的结点,移动指针指向即可。
40             {
41                 pre = cur;
42                 cur = cur->next;
43             }
44         }
45         
46         // 将两部分连接起来
47         // 将原始链表中小于x(< x)的部分和原始链表中大于等于x(>= x)的部分连接起来
48         pre->next = pNew->next;
49         head = pHead->next;
50         
51         // 释放辅助结点内存空间
52         delete pHead;
53         delete pNew;
54         
55         return head;
56     }
57 };

086. Partition List

标签:def   you   nal   过程   ptr   大于   lan   get   input   

原文地址:https://www.cnblogs.com/ming-1012/p/9938882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!