Leetcode Topic Description:
Remove all elements from a linked list of integers, that has value val.
Example
Given: 1---2--and 6---3---4---5, val = 6
Return: 1--2--and 3--4--5
Generate linked List
If the input element is not 0, it is added to the tail of the list, if 0, does not join, and the resulting list work is completed. The code is as follows:
ListNode * Creat_list () {ListNode *p,*head,*s;head= (listnode*) malloc (sizeof (ListNode));p =head;int flag=1;int x;while (flag) {cin>>x;if (x!=0) {s= (listnode*) malloc (sizeof (ListNode)); s->val=x;p->next=s;p=s;} elseflag=0;} P->next=null;head=head->next;return Head;}
Remove an element code from the list as follows:
listnode* removeelements (listnode* head, int val) {if (head==null) return head; ListNode *p,*s;p=head;while (P!=null) {while (val!=p->val&&p->next!=null) {s=p;p=p->next;} if (val==p->val) {if (val==head->val) {head=head->next;} Else{s->next=p->next;}} P=p->next;} return head;}
The complete code is as follows:
#include <iostream>using namespace std;struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; ListNode * Creat_list (); listnode* removeelements (listnode* head, int val), void Main () {ListNode *head,*head1,*p;head=creat_list ();p =head; while (p) {cout<<p->val<< "";p =p->next;} Cout<<endl;head1=removeelements (Head, 6);p =head1;while (p) {cout<<p->val<< "";p =p->next;} Cout<<endl;} ListNode * Creat_list () {ListNode *p,*head,*s;head= (listnode*) malloc (sizeof (ListNode));p =head;int flag=1;int x;while (flag) {cin>>x;if (x!=0) {s= (listnode*) malloc (sizeof (ListNode)); s->val=x;p->next=s;p=s;} elseflag=0;} P->next=null;head=head->next;return Head;} listnode* removeelements (listnode* head, int val) {if (head==null) return head; ListNode *p,*s;p=head;while (P!=null) {while (val!=p->val&&p->next!=null) {s=p;p=p->next;} if (val==p->val) {if (val==head->val) {head=head->next;} Else{s->neXt=p->next;}} P=p->next;} return head;}
The results of the operation are as follows:
That is, generate a list of 6-1-2-3-6-7-8-9-6, delete the node where the value is 6, and get the result as 1-2-3-7-8-9
Generate a one-way linked list and delete an element in the linked list