leetcode 题目描述:
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
生成链表
若输入元素不为0,则加入到链表尾部,若为0,不加入,且生成链表工作完成。代码如下:
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; } else flag=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; }
完整代码如下:
#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; } else flag=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; }
运行结果如下:
即生成链表为6-1-2-3-6-7-8-9-6,删除其中值为6的节点,得到结果为 1-2-3-7-8-9
时间: 2024-10-27 05:29:16