1. 首页 > 科技

求助大神单链表算法题 用c语言求链表长度

求助大神单链表算法题用c语言求链表长度

求助大神!用C完成对单链表的操作

/**

*

*百度知道

*

*/

#include

#include

#define N 50

struct list

{

int num;

struct list *next;

};

//链表创建

struct list *creat()

{

int value;

struct list *baidu,*p,*q;

baidu = (struct list *)malloc(sizeof(struct list) * N);

q = baidu;

printf("开始输入整数(输入-1退出):");

scanf("%d",&value);

while(value>0)

{

p=(struct list *)malloc(sizeof(struct list) );

p->num = value;

q->next = p;

q = p;

printf("继续输入(输入-1退出):");

scanf("%d",&value);

}

q->next = NULL;

return baidu;

}

//链表打印

void print(struct list *baidu)

{

struct list *p;

p = baidu->next;

while(p!=NULL)

{

printf("%d ",p->num);

p=p->next;

}

printf("\n");

}

//链表长度

int length(struct list *baidu)

{

int _length = 0;

struct list *p;

p = baidu->next;

while(p!=NULL)

{

_length++;

p=p->next;

}

return _length;

}

//插入

void insert(struct list *baidu)

{

struct list *p,*q,*t;

int pos;

int insert_value;

int flag = 1;//记录当前是否位于指定插入的位置

p = t = baidu->next;

printf("输入插入位置:");

loop:

scanf("%d",&pos);

if(pos<=0||pos>length(baidu))

{

printf("无效插入位置!,重新输入:");

goto loop;

}

printf("输入插入值:");

scanf("%d",&insert_value);

q=(struct list *)malloc(sizeof(struct list));

q->num = insert_value;

while(flag!=pos)

{

t = p;

flag++;

p=p->next;

}

if(t == baidu->next)

{

q->next = baidu->next;

baidu->next = q;

return;

}

q->next = t->next;

t->next = q;

}

//删除

void _delete(struct list *baidu)

{

struct list *p,*t;

int flag = 0;//同插入

int pos;

p = t = baidu;

printf("输入删除位置:");

loop:

scanf("%d",&pos);

if(pos<=0||pos>length(baidu))

{

printf("无效删除位置!,重新输入:");

goto loop;

}

while(flag!=pos&&p->next!=NULL)

{

t = p;

flag++;

p=p->next;

}

t->next = p->next;

free(p);

}

int main(void)

{

struct list *baidu;

baidu = creat();

print(baidu);

insert(baidu);

print(baidu);

_delete(baidu);

print(baidu);

return 0 ;

}

全部手打 环境:VC++ win8.1 自己多研究 一下 这个题方法很多 才开始 自己多动手试试