结构体定义:
struct Node{
int data;
struct Node *next;
};
链表的创建:
struct Node* initLink()
{
struct Node *head;
struct Node *tail;
struct Node *newNode;
head=(struct Node*)malloc(sizeof(struct Node));
head->next=NULL;
head->data=0;
tail=head;
int i;
for(i=1;i<=10;i++)
{
newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->next=NULL;
newNode->data=i;
tail->next=newNode;
tail=newNode;
}
return head;
}
链表的遍历:
void printLink(struct Node *head)
{
struct Node *p;
p=head;
while(p!=NULL)
{
printf("data=%d\n",p->data);
p=p->next;
}
}
链表的插入:
void insertNode(struct Node *head,int weizhi,struct Node *node)
{
struct Node *p;
p=head;
while(p!=NULL)
{
if(p->data==weizhi)
{
node->next=p->next;
p->next=node;
}
p=p->next;
}
}
链表的删除:
int delateNode(struct Node *head,int data)
{
struct Node *p;
struct Node *tmp;
p=head;
while(p!=NULL && p->next !=NULL)
{
if(p->next->data == data)
{
break;
}
p=p->next;
}
if(p->next==NULL)
{
return -1;
}
tmp=p->next;
p->next=tmp->next;
free(tmp);
return 0;
}