关闭

LeetCode-Remove Linked List Elements-解题报道

标签: leetcodeC++
116人阅读 评论(0) 收藏 举报
分类:

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

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5 


就是删除链表中所有对应值的节点。


先看是否需要删除头,然后在判断中间的。


/**
 * 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 *pre, *current;
		pre = head;
		current = head->next;
		while (pre != NULL && pre->val == val)
		{
			pre = current;
			if (pre != NULL)
				current = pre->next;
		}
		head = pre;
		while (current != NULL)
		{
			if (current->val == val)
				pre->next = current->next;
			
			else
				pre = current;
			current = current->next;
		}
		return head;
	}
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15647次
    • 积分:851
    • 等级:
    • 排名:千里之外
    • 原创:72篇
    • 转载:6篇
    • 译文:0篇
    • 评论:0条
    文章分类