【数据结构】链表相关练习题:链表分割

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

分析:

这道题的思路是创建一个less和一个greater节点,把他们看作头结点,然后去遍历原链表,如果遍历的值cur比x小,就把cur尾插在less节点的后面,如果遍历的值cur比x大,就把cur链在greater节点的后面,遍历完之后,再让less的tail指向greater,最后释放掉less和greater两个节点。

具体代码如下:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        if(pHead==NULL)
        {
            return NULL;
        }
       struct ListNode* less_head,*less_tail;
       struct ListNode* greater_head,*greater_tail;
       less_head=less_tail=(struct ListNode*)malloc(sizeof(struct ListNode));
       greater_head=greater_tail=(struct ListNode*)malloc(sizeof(struct ListNode));  
       struct ListNode* cur=pHead;
        
       while(cur)
        {
            if(cur->val<x)
         {
          less_tail->next=cur;
          less_tail=less_tail->next;
         }
        else
        {
          greater_tail->next=cur;
          greater_tail=greater_tail->next;
        }
           cur=cur->next;
        }
       less_tail->next=greater_head->next;
        greater_tail->next=NULL;
        
        pHead=less_head->next;
        free(less_head);
        free(greater_head);
        
        return pHead;
    }
};

oj链接:https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId

猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/83034270