看链表的时候,总有个问题特别纠结,到底要还是不要头结点!!!
后来发现,要不要都无所谓;当然,网上也有论文专门讨论头结点的用处,这里就不多写了,先把具体功能实现再说吧。
typedef int ElemType;
typedef struct node Node;
typedef struct node SeqList;
struct node
{
ElemType data;
Node *next;
};
SeqList *CreateList()
{
SeqList *sq;
sq = (SeqList *)malloc(sizeof(Node));
if(sq == NULL) exit(OVERFLOW);
sq->next = NULL;
return sq;
}
//在表尾插入数据
void InsertAfter(SeqList *L,ElemType e)
{
SeqList *p = L;
Node *q;
q = (Node *)malloc(sizeof(Node));
q->data = e;
q->next = NULL;
while(p->next)
p = p->next;
p->next = q;
}
//找出第index个结点
Node *FindList(SeqList *L,int index)
{
int count = index;
Node *p = L;
if(count < 0)return NULL;
if(p == NULL)return NULL;
while(p->next != NULL && count>=0)
{
p = p->next;
count--;
}
if (count >= 0) {printf("表不够长!");return NULL;}
return p;
}
//在第index位置插入数据
bool InsertList(SeqList *L,int index,ElemType e)
{
Node *p = FindList(L,index);
Node *q;
q = (Node*)malloc(sizeof(Node));
q->data = e;
q->next = p->next;
p->next = q;
return true;
}
//在第index位置删除数据
bool DeleteList(SeqList *L,int index)
{
Node *p = FindList(L,index);
Node *q;
q = (Node *)malloc(sizeof(Node));
q = p->next;
p->next = p->next->next;
free(q);
return true;
}
//表是否为空
bool IsEmpty(SeqList *L)
{
return (L->next == NULL);
}
//遍历表
void showList(SeqList *L)
{
SeqList *q = L;
while (q->next)
{
q = q->next;
printf("%d ",q->data);
}
printf("\n");
}
还是跟动态分配一样,测试代码。。。
int _tmain(int argc, _TCHAR* argv[])
{
SeqList *L = CreateList();
int i;
for (i = 1;i < 10;i++)InsertAfter(L,i);
printf("新建表,插入9个元素:");
showList(L);
printf("在第3个位置插入100:");
InsertList(L,2,100);
showList(L);
printf("将第5个位置的数据删除:");
DeleteList(L,4);
showList(L);
return 0;
}
希望大家帮指点,不足的地方能帮我进步的。。。