从链表中移除节点(leetcode)

题目链接:. - 力扣(LeetCode)


方法一:翻转链表

思路:

当右侧有更大值  就需要移除

翻转后 左侧有更大值  就需要移除

翻转后   8   3    13    2     5     定义一个最大值max  == 第一个节点的值依次迭代

                  max = 8

                        max = 13

struct ListNode* reserve(struct ListNode* head )

{

    struct ListNode* p1 = NULL;

    struct ListNode* p2 = head;

    struct ListNode* p3 = head->next;

    while( p2 )

    {

        p2->next = p1;

        p1 = p2;

        p2 = p3;

        if( p3 )p3 = p3->next;

    }

    return p1;

}

struct ListNode* removeNodes(struct ListNode* head)

{

    struct ListNode* phead = reserve(head);

    struct ListNode* prev = phead;

    struct ListNode* temp = phead;

    int max = prev->val;

    phead = phead->next;

    while( phead )

    {

        if( phead->val < max )

        {

            prev->next = phead->next;

            phead = prev->next;

        }

        else

        {

            prev = phead;

            max = phead->val;

            phead = phead->next;

        }

    }

    return reserve(temp);

}

方法二:递归法

struct ListNode *removeNodes(struct ListNode *head) {
    if (head == NULL) {
        return NULL;
    }
    head->next = removeNodes(head->next);
    if (head->next != NULL && head->val < head->next->val) {
        return head->next;
    } else {
        return head;
    }
}

方法三:栈

int len(struct ListNode *head) {
    int n = 0;
    while (head != NULL) {
        n++;
        head = head->next;
    }
    return n;
}

struct ListNode *removeNodes(struct ListNode *head) {
    struct ListNode **st = (struct ListNode **)malloc(sizeof(struct ListNode *) * len(head));
    int top = -1;
    for (; head != NULL; head = head->next) {
        top++;
        st[top] = head;
    }
    for (; top >= 0; top--) {
        if (head == NULL || st[top]->val >= head->val) {
            st[top]->next = head;
            head = st[top];
        }
    }
    return head;
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值