欢迎大家访问我的微博:http://weibo.com/u/2887401030
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LinkListNode
{
ElemType data;
struct LinkListNode *next;
}LinkListNode;
typedef struct LinkList
{
LinkListNode head;
int length;
}LinkList;
LinkList* Create_List()
{
LinkList *list = (LinkList *)malloc(sizeof(LinkList));
if(list == NULL)
{
return NULL;
}
list->head.data = 0;//在这里,头地址的data设为0
list->head.next = NULL;
list->length = 0;
return list;
}
int Insert_List(LinkList *list,int pos,ElemType data)
{
LinkListNode *node = NULL,*cur = NULL;
int i;
if(list == NULL)
{
return -1;
}
if(pos < 0 || pos > list->length)
{
return -2;//第一个,...,最后一个的后面一个(未创建)可以
}
node = (LinkListNode *)malloc(sizeof(LinkListNode));
if(node == NULL)
{
return -2;
}
node->data = data;
node->next = NULL;
cur = &list->head;
// 0 1 2 3 4
//head 1 5 3 7 4 . .
for(i=0;i<pos && cur->next != NULL;i++)
{
cur = cur->next;//后移,知道pos之前的位置
}
//别被顺序结构的搞混了
//此时cur就是要插入的之前那个结点
node->next = cur->next;
cur->next = node;
list->length++;
return 0;
}
int Delete_List(LinkList *list,int pos,ElemType *value)
{
LinkListNode *cur = NULL,*tmp = NULL;
int i;
if(list == NULL)
{
return -1;
}
if(pos < 0 || pos > list->length)
{
return -2;
}
//容错,
if(pos == list->length)
{
pos--;
}
cur = &list->head;
// 0 1 2 3 4
//head 1 5 3 7 4 . .
for(i=0;i<pos&& cur->next != NULL;i++)
{
cur = cur->next;
}
tmp = cur->next;
cur->next = tmp->next;
*value = tmp->data;
free(tmp);
list->length--;
return 0;
}
int Get_List(LinkList *list,int pos,ElemType *value)
{
LinkListNode *cur = NULL;
int i;
if(list == NULL)
{
return -1;
}
if(pos < 0 || pos > list->length)
{
return -2;
}
//容错,
if(pos == list->length)
{
pos--;
}
cur = &list->head;
// 0 1 2 3 4
//head 1 5 3 7 4 . .
for(i=0;i<pos&& cur->next != NULL;i++)
{
cur = cur->next;
}
*value = cur->next->data;
return 0;
}
void Destroy_List(LinkList *list)
{
LinkListNode *cur = NULL,*tmp = NULL;
if(list == NULL)
{
return;
}
cur = list->head.next;//头节点之后的节点
//头结点 0 1 2 3 4
// head 1 5 3 7 4 . .
while(cur->next != NULL)
{
tmp = cur->next;
free(cur);
cur = tmp;
}
free(cur);//删除最后一个
free(list);//释放整个list
}
int main()
{
int i = 0,value = 0;
LinkList *list = Create_List();
if(Insert_List(list,list->length+1,100) != 0)
{
printf("insert error\n");
}
for(i=0;i<10;i++) //故意多一个
{
if(Insert_List(list,i,list->length) != 0)
{
printf("insert %d error\n",i);
}
}
for(i=0;i<list->length;i++)
{
Get_List(list,i,&value);
printf("%2d ",value);
}
Delete_List(list,0,&value);
printf("\ndelete num:%d\n",value);
Destroy_List(list);
return 0;
}
结果:
insert error
0 1 2 3 4 5 6 7 8 9
delete num:0
从结果看出,我们故意在length之后的位置在insert的数字出错了,其他的也都在我们的意料之中。我们这里的结构体与某些教科书上可能有点不一样。有些教科书上是这样写的:
typedef struct node
{
ElemType data;
struct Node *next;
}Node;
typedef struct Node *LinkList;//定义LinkList
我个人不喜欢这种风格,直接把节点当成整个链表,同时又直接是指针类型。我还是喜欢直接把LinkList定义出来,用户Create出来后,就会获得LinkList*的变量,用这个变量就能操控一切。我的这篇文章就是按这样的风格写的。