zoukankan      html  css  js  c++  java
  • 【LeetCode】Partition List ——链表排序问题

    【题目】

    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.

    For example,
    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5.

    【解析】

    题意:给定一个单链表和一个x,把链表中小于x的放到前面,大于等于x的放到后面,每部分元素的原始相对位置不变。

    思路:其实很简单,遍历一遍链表,把小于x的都挂到head1后,把大于等于x的都放到head2后,最后再把大于等于的链表挂到小于链表的后面就可以了。

     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         ListNode lessHead(0);
    13         ListNode greatHead(0);
    14         ListNode *cur=head,*less=&lessHead,*great=&greatHead;
    15         while(cur!=NULL){
    16             ListNode *next=cur->next;
    17             if(cur->val<x){
    18                 less->next=cur;
    19                 less=less->next;
    20                 less->next=NULL;
    21             }
    22             else{
    23                 great->next=cur;
    24                 great=great->next;
    25                 great->next=NULL;
    26             }
    27             cur=next;
    28         }
    29         less->next=greatHead.next;
    30         return lessHead.next;
    31     }
    32 };
  • 相关阅读:
    Linux的SSH(Secure Shell Protocol)服务
    Linux开机自动挂载文件fstab介绍
    Linux之NFS网络文件系统
    深入理解sudo
    Linux定时任务(crond)
    Linux之Vim编辑器的使用
    三大文本处理工具grep、sed及awk
    jquery实现自定义弹出框
    oarcle12c打开本地数据库
    使用POI将doc文件转换为html
  • 原文地址:https://www.cnblogs.com/zl1991/p/7070090.html
Copyright © 2011-2022 走看看