第二次作业
1. 试比较顺序存储结构和链式存储结构的优缺点。
在什么情况下用顺序表比链表好?
2 .描述以下三个概念的区别:头指针、头结点、首元结点(第一个元素结点)。
在单链表中设置头结点的作用是什么?
3.已知P结点是双向链表的中间结点,试从下列提供的答案中选择合适的语句序列。
a.在P结点后插入S结点的语句序列是-----------。
b.在P结点前插入S结点的语句序列是-----------。
c.删除P结点的直接后继结点的语句序列是----------。
d.删除P结点的直接前驱结点的语句序列是----------。
e.删除P结点的语句序列是------------。
(1)P->next=P->next->next; (10) P->prior->next=P;
(2)P->prior=P->prior->prior; (11) P->next->prior =P;
(3) P->next=S; (12)P->next->prior=S;
(4) P->prior=S; (13) P->prior->next=S;
(5)S->next=P; (14) P->next->prior=P->prior
(6)S->prior=P; (15)Q=P->next;
(7) S->next= P->next; (16)Q= P->prior;
(8) S->prior= P->prior; (17)free(P);
(9) P->prior->next=p->next; (18)free(Q);
4. 编写程序,将若干整数从键盘输入,以单链表形式存储起来,然后计算单链表中结点的个数(其中指针P指向该链表的第一个结点)。
#include<stdio.h> //输入-1时输入结束#include<malloc.h>
typedef struct node //定义链表节点
{int data;
struct node *next;
}List;
int countNode(List *h) //节点计数
{List *p=h;
int i=1;
p=p->next;
while(p!=NULL)
{printf("%d\t",p->data);
i++;
p=p->next;
}
putchar('\n');
return i-1;
}
main()
{int a;
List *head,*p,*s;
p=head=(List *)malloc(sizeof(List));
while(1)
{
puts("Input:");
scanf("%d",&a);
getchar();
if(a!=-1)
{s=(List *)malloc(sizeof(List));
s->data=a;
s->next=NULL;
p->next=s;
p=p->next;}
else break;
}
printf("The sum is %d",countNode(head));
}。