c语言实现单链表操作

#include <stdio.h>

#include <malloc.h>


typedef struct Node{

int data;

struct Node *next;

}Node,*Link;


Node * init(int len)//初始化链表

{

int i;

Node *head,*p,*q;


head=(Link)malloc(sizeof(Node));

p=head;

for(i=0;i<len;i++)

{

q=(Link)malloc(sizeof(Node));

q->data=2*i;

q->next=NULL;

p->next=q;

p=q;

head->data++;

}

return head;

}


Node * insert(Node *hm,int x)//插入节点

{

Node *m,*tmp;

m=hm->next;

tmp=(Link)malloc(sizeof(Node));

tmp->data=x;

tmp->next=NULL;

while(m->next!=NULL)

{

if(x>m->data&&x<=m->next->data)

{

tmp->next=m->next;

m->next=tmp;

hm->data++;

}

m=m->next;

}

if(x>m->data)

{

m->next=tmp;

hm->data++;

}

return hm;

}


Node * delete(Node *hm,int x)//删除节点

{

int bool=0;

Node *m,*tmp;

m=hm;

while(m->next!=NULL)

{

if(m->next->data==x)

{

tmp=m->next;

m->next=tmp->next;

free(tmp);

bool=1;

hm->data--;

}

if(m!=NULL)

{m=m->next;}

if(m==NULL){break;}

}

if(bool==0){printf("there is no this kind of node:%d\n",x);}

return hm;

}


//链表逆序http://blog.csdn.net/niuer09/article/details/5961004

Node * reverse(Node *hm)//链表逆序

{

if(hm->next==NULL||hm->next->next==NULL)

{return hm;}

Node *t=NULL,*p=hm->next,*q=p->next;

while(q!=NULL)

{

t=q->next;

q->next=p;

p=q;

q=t;

}

hm->next->next=NULL;

hm->next=p;

return hm;

}


void play(Node *m)//打印节点

{

while(m!=NULL)

{

printf("%d ",m->data);

m=m->next;

}

printf("\n");

}


void main(int argc,char *argv[])

{

int len,insertnum,deletenum;

Node *l;

len=atoi(argv[1]);

insertnum=atoi(argv[2]);

deletenum=atoi(argv[3]);

l=init(len);

l=insert(l,insertnum);

play(l);

}


你可能感兴趣的:(c,链表)