[LeedCode OJ]#203 Remove Linked List Elements

【 声明:版权所有,转载请标明出处,,请勿用于商业用途。 联系信箱: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;}};

版权声明:本文为博主原创文章,如果转载,请注明出处

哪怕前方的路会充满坎坷,但为梦想而拼搏的人会永不言败

[LeedCode OJ]#203 Remove Linked List Elements

相关文章:

你感兴趣的文章:

标签云: