0
点赞
收藏
分享

微信扫一扫

分割链表(牛客网)

悲催博士僧 2022-04-17 阅读 78

现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        //设置哨兵位头节点
       struct ListNode*lesshead,*lesstail,*greaterhead,*greatertail,*cur;
        lesshead=lesstail=(struct ListNode*)malloc(sizeof(struct ListNode));
        lesstail->next=NULL;
      greaterhead=greatertail=(struct

ListNode*)malloc(sizeof(struct ListNode));
       greatertail->next=NULL;
        cur=pHead;
        while(cur)
        {
            if(cur->val<x)
            {
                lesstail->next=cur;
                lesstail=cur;
            }
            else{
                greatertail->next=cur;
                greatertail=cur;
            }
            cur=cur->next;
        }
        lesstail->next=greaterhead->next;
        greatertail->next=NULL;
        struct ListNode*newhead=lesshead->next;
        free(lesshead);
        free(greaterhead);
        
        return newhead;
    }
    
};

举报

相关推荐

0 条评论