当前位置: 代码迷 >> C语言 >> [求助]请大家帮我看个程序(关于链表的)
  详细解决方案

[求助]请大家帮我看个程序(关于链表的)

热度:111   发布时间:2007-03-30 23:30:51.0
[求助]请大家帮我看个程序(关于链表的)

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# define NULL 0
# define LEN sizeof(struct node)


struct node{
int data;
struct node *next;
};

struct node *Head;


struct node * Init_list(void)
{
struct node *head;
head=(struct node *)malloc(LEN);
if(head)
{
head->next=NULL;
}
return (head);
}


struct node * creat_list(int n)
{
int i;
struct node *p1,*p2,*p3;
p3=p2=(struct node *)malloc(LEN);
for(i=0;i<n;i++)
{
p1=(struct node *)malloc(LEN);
p2->next=p1;
p2=p1;
i++;
}
p2->next=NULL;
return(p3);
}


void input(struct node * head)
{
struct node *p1;
p1=head->next;
while(p1)
{
scanf("%d ",&p1->data);
p1=p1->next;
}
}

void output(struct node *head)
{
struct node *p2;
p2=head->next;
while(p2)
{
printf("%d ",p2->data);
p2=p2->next;
}
}

void insert_list(int n,int m,struct node *head)
{
int i;
struct node *p;
struct node *q;
p=head;
q=(struct node *)malloc(LEN);
printf("Please input the data in node q;\n");
if(n>m)
{
printf("fail to insert\n");
}
for(i=0;i<=m;i++)
{
if(i!=n)
{
p++;
}
else
{
q->next=p->next;
p->next=q;
m+=1;
printf("Success.\n");
}
}
}


void delete_list(int n,int m,struct node * head)
{
int i;
struct node *p1,*p2;
p1=head;
if(n>m)
{
printf("fail to detele.\n");
}
for(i=0;i<m;i++)
{
if(i!=n)
{
p2=p1;
p1=p1->next;
}
else
{
p2->next=p1->next;
p1->next=NULL;
m-=1;
printf("Success.\n");
printf("delete %d\n",p1->data);
}
}
}


void main()
{
struct node *p,*q;
int m,n;
int Len=0;
Head=Init_list();
printf("Please input the length of the list:\n");
scanf("%d,&Len");
Head->next=creat_list(Len);
printf("Now,you will input the numbers into the list.\n");
input(Head);
printf("Now,please check these data.\n");
output(Head);
p=(struct node *)malloc(LEN);
p->next=Head->next;
Head->next=p;
q=(struct node *)malloc(LEN);
printf("Now,please locate the inserted seat.\n");
scanf("%d",&n);
insert_list(n,Len,Head);
output(Head);
printf("Now,please locate the deleted seat.\n");
scanf("%d",&m);
delete_list(m,Len,Head);
output(Head);
printf("\n");
}

链表的创建,插入,删除



搜索更多相关的解决方案: 链表  

----------------解决方案--------------------------------------------------------
太长了啊。

----------------解决方案--------------------------------------------------------
回复:(QQ0001000)怎么了。有什么不懂的么。这样的程...
这是数据结构的程序,链表的创造,添加,删减
问题出在input函数,假如我建立了五个结点,应该输入五个数就跳出来,单现在得输六个数他才能出来,为什么?
还有就是,如果我把链表的长度作为形参放在create函数中时,程序会出错,提示len(链表长度)是重要内存,无法使用,要不就是错,这又是怎么了?
谢谢
----------------解决方案--------------------------------------------------------
  相关解决方案