[LeedCode OJ]#203 Remove Linked List Elements

来源:互联网 发布:理财成功案例知乎 编辑:程序博客网 时间:2024/06/16 18:49

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


题目链接:https://leetcode.com/problems/remove-linked-list-elements/


题意:

给定一个链表和一个数x,要求删除链表中所有与x相等的结点,返回新的链表


思路:

很简单,直接遍历整个链表,一旦找到与x相等的结点就直接跳过,对于连续几个与x相等的结点要小心处理


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public:ListNode* removeElements(ListNode* head, int val){while(head && head->val==val)head = head->next;ListNode *cur = head;ListNode *newlist = new ListNode(0);ListNode *ptr = newlist;while(cur){while(cur && cur->val == val)cur = cur->next;if(cur==nullptr)break;ListNode *pnext = cur->next;ptr->next = cur;cur = pnext;ptr = ptr->next;}ptr->next = nullptr;return newlist->next;}};


0 0
原创粉丝点击