码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode203. Remove Linked List Elements

时间:2018-09-24 00:26:46      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:turn   int   code   tno   循环   str   element   问题   efi   

很经典的一道题,但波波老师讲出了新的东西。设立虚拟结点,因为每次循环cur->next只有头结点无法考虑,但是你要是单独考虑头结点,万一头结点删除你还需要再考虑下一头结点,就形成了很麻烦的while结构。有了虚拟头结点,问题全都解决了。

/**
* 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) {
		if (head == NULL)
			return NULL;
		ListNode* dummyhead;
		dummyhead = new ListNode(0);
		dummyhead->next = head;
		ListNode* cur;
		cur = dummyhead;
		while (cur->next!=NULL)
		{
			if (cur->next->val == val)
			{
				ListNode* delNode;
				delNode = cur->next;
				cur->next = delNode->next;
				delete delNode;
			}
			else
			cur = cur->next;
		}
		return dummyhead->next;
	}
};

  

leetcode203. Remove Linked List Elements

标签:turn   int   code   tno   循环   str   element   问题   efi   

原文地址:https://www.cnblogs.com/legendcong/p/9693837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!