• 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.

    思路:

    1.由于不能改变原来的相对位置,所以直接置换值是不行的。

    2.其实这个题类似于快速排序的Partition函数,该思路是,随机从数组中选取一个值作为参考值,使得数组中比该参考值小的数字排在参考值左端,数组中比该参考值大的数字排在参考值右端

    遍历所有节点,发现比x小的节点就”交换“,交换的过程即先删除那个节点,然后插入到对应位置。

    这里有一个前提,即若第一个数就小于x的话,是不需要“交换的”。

    另外一点需要注意的是:删除链表某个节点之后,指针p的值可能出现不定义状态,故在删除之前,先让p指向要删除节点的下一个节点。

     class Solution {
     public:
         //删除链表中位置为loc的节点,从1开始
         int Delete(ListNode* &head,int loc){
             ListNode* p=NULL;
             ListNode* q=NULL;
             p=head;
             int i=1;
             //找到前驱节点
             while(i<loc-1&&p->next){
                 ++i;
                 p=p->next;
             }
             q=p->next;
             p->next=q->next;
    
             int val=q->val;
             free(q);
             return val;
         }
         ListNode* Insert(ListNode* &head,int loc,int val){
             ListNode* p=head;
             p=head;
             int i=1;
             if(loc==1){
                 ListNode* s=(ListNode*)malloc(sizeof(ListNode));
                 s->val=val;
                 s->next=p;
                 return s;
             }
             //找到前驱节点
             while(i<loc-1&&p->next){
                 ++i;
                 p=p->next;
             }
             ListNode* s=(ListNode*)malloc(sizeof(ListNode));
             s->val=val;
             s->next=p->next;
             p->next=s;
             return head;
         }
         ListNode *partition(ListNode *head, int x) {
             if(head==NULL) return NULL;
             int insertloc=0;
             int loc=0;
             ListNode* p=head;
             while(p!=NULL)
             {
                 ++loc;
                 if(p->val<x)
                 {
                     ++insertloc;
                     if(insertloc!=loc){
                         p=p->next;
                         int val=Delete(head,loc);
                         head=Insert(head,insertloc,val);
                         continue;
                     }
                 }
                 p=p->next;
             }
             return head;
         }
     };
  • 相关阅读:
    剑指offer-最小的k个数
    剑指offer-数组中出现次数超过一半的数字
    android开发------响应用户事件
    android开发------初识Activity
    android开发------编写用户界面之相对布局
    android开发------编写用户界面之线性布局(补充知识)
    android开发------编写用户界面之线性布局
    android开发------第一个android程序
    加密狗的工作原理
    克隆加密狗、复制加密狗、破解加密狗的定义区别
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4176784.html
Copyright © 2020-2023  润新知