实现函数CreateHeader用于创建空链表,实现Insert函数并调用它完成带头节点链表的创建。
部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。
void PrintLinkList(Node *head)
{
int flag = 0;
Node *p = head->next, *q;
while§
{
if(flag)
printf(" “);
flag = 1;
printf(”%d", p->data);
q = p;
p = p->next;
free(q);
}
free(head);
}
int main()
{
int n, d;
Node *head;
CreateHeader(&head);
scanf("%d", &n);
while(n–)
{
scanf("%d", &d);
Insert(head, d);
}
PrintLinkList(head);
return 0;
}
输入
输入数据第一行为n,表示链表元素个数,第二行为n个整数,表示节点元素值(所有元素值不相等)。
第三行为删除的元素值,一定存在于链表中。
输出
输出删除后的链表元素,每个元素值之间用一个空格隔开。
样例输入
5
1 2 3 4 5
3
样例输出
1 2 4 5
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node;
Node *CreateLinkList(int n)
{
Node*head,*p;
head=(Node*)malloc(sizeof(Node));
head->next=NULL;
p=head;
while(n--)
{
int a;
scanf("%d",&a);
p->next=(Node*)malloc(sizeof(Node));
p=p->next;
p->data=a;
p->next=NULL;
}
return head;
}
Node *Find(Node* head,int n)
{
Node*p;
p=head;
while(p->next->data!=n)
{
p=p->next;
}
return p;
}
Node Delete(Node*p)
{
Node *q;
q=(Node*)malloc(sizeof(Node));
q=p->next;
p->next=q->next;
free(q);
}
void PrintLinkList(Node *head)
{
int flag = 0;
Node *p = head->next, *q;
while(p)
{
if(flag)
printf(" ");
flag = 1;
printf("%d", p->data);
q = p;
p = p->next;
free(q);
}
free(head);
}
int main()
{
int n, x;
scanf("%d", &n);
Node *head = CreateLinkList(n);
scanf("%d", &x);
Node *p = Find(head, x);
Delete(p);
PrintLinkList(head);
return 0;
}