leetcode 203. Remove Linked List Elements

来源:互联网 发布:放置江湖武功数据排行 编辑:程序博客网 时间:2024/05/22 00:05

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

就是遍历链表删除所有的target元素,注意对头结点的特殊处理。

代码如下:

/*class ListNode {      int val;      ListNode next;      ListNode(int x) { val = x; }}*//* * 这个是单链表的元素删除问题  * */public class Solution {    public ListNode removeElements(ListNode head, int val)     {        //首先要处理头部的元素        while(head!=null)        {            if(head.val==val)                head=head.next;            else                 break;        }        if(head==null)            return head;        //这是处理其余的元素        ListNode fa=head;        while(fa.next!=null)        {            if(fa.next.val==val)                fa.next=fa.next.next;            else                fa=fa.next;        }        return head;    }}

下面是C++的做法,就是做一个遍历即可

代码如下:

#include <iostream>#include <vector>#include <string>#include <map>#include <set>#include <cmath>#include <queue>#include <stack>#include <algorithm>using namespace std;/*struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {}};*/class Solution{public:    ListNode* removeElements(ListNode* h, int val)    {        if (h == NULL)            return h;        ListNode* head = new ListNode(-1);        head->next = h;        ListNode* i = head->next;        ListNode* fa = head;        while (i != NULL)        {            if (i->val == val)            {                fa->next = i->next;                i = fa->next;            }            else            {                fa = i;                i = i->next;            }        }        return head->next;    }};
原创粉丝点击