6-2 Removal for Linked-list (10 分)
This a linked-list program that reads unknown amount of non-negative integers. -1 is used to indicates the end of the input process. Then the program reads another integer and find all apprearence of this integer in the previous input and remove them. Finally the program prints out the remainning integers.
You are required to implement list_append() and list_remove() functions.
函数接口定义:
void list_append(List *list, int value);
void list_remove(List *list, int value);
For list_append(), list is the pointer to the List variable, and value is the integer value to be added into the list.
For list_remove(), list is the pointer to the List variable, and value is the integer value to be removed from the list. Notice that there may be more than one value in the list.
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Node {
int value;
struct _Node *next;
struct _Node *prev;
} Node;
typedef struct {
Node *head;
Node *tail;
} List;
void list_append(List *list, int value);
void list_remove(List *list, int value);
void list_print(List *list);
void list_clear(List *list);
int main()
{
List list = {NULL, NULL};
while ( 1 ) {
int x;
scanf("%d", &x);
if ( x == -1 ) {
break;
}
list_append(&list, x);
}
int k;
scanf("%d", &k);
list_remove(&list, k);
list_print(&list);
list_clear(&list);
}
void list_print(List *list)
{
for ( Node *p = list->head; p; p=p->next ) {
printf("%d ", p->value);
}
printf("\n");
}
void list_clear(List *list)
{
for ( Node *p = list->head, *q; p; p=q ) {
q = p->next;
free(p);
}
}
/* 请在这里填写答案 */
输入样例:
1 2 3 4 5 6 -1
3
结尾无空行
输出样例:
1 2 4 5 6
结尾无空行
代码展示:
void list_append(List *list, int value)
{
// printf("111\n");
Node *p=(Node*)malloc(sizeof(Node));
p->value=value;
if(list->head==NULL)
{
list->head=p;
list->head->prev=NULL;
list->tail=list->head;
list->tail->next=NULL;
}
else
{
list->tail->next=p;
p->prev=list->tail;
p->next=NULL;
list->tail=p;
}
}
void list_remove(List *list, int value)
{
//p为原链表,q为没有value的链表
Node *p=list->head;
Node *head=(Node*)malloc(sizeof(Node));
Node *q=head,*tem;
q->next=NULL;
while(p)
{
tem=p;
if(p->value!=value)
{
q->next=tem;
q=q->next;//始终指向尾部
p=p->next;
}
else
{
p=p->next;
free(tem);
}
}
//q就是完整的带有头结点没有value的链表
q->next=NULL;//一定要保证尾结点的next为NULL!!(万一删除了最后一个元素)
tem=head;
head=head->next;
free(tem);//多余的头结点删除
list->head=head;
list->tail=q;
}
一个链表删除多个结点想办法如何去换位思考?
对于链表尾部的处理又有什么样的注意事项?