高手:数据结构的有关问题
请教各位高手:数据结构的问题
struct node{
char *name;
struct node *next;
};
struct node *Head;
Head为单向链表头,并按照其成员变量name的字符序大小排列。
分别编写函数添加和删除一个struct node类型的结点。
------解决方案--------------------
添加:逐个节点遍历,直到找到正确的插入位置。
删除:逐个节点遍历,直到找到需要删除的节点。
都是一些基本的指针操作,没什么复杂的,自己试试看。
------解决方案--------------------
//线性链表插入,删除操作
#include <stdio.h>
#include <malloc.h>
typedef struct LNode
{int data;
struct LNode *next;
}LNode,*linklist;
int Init(linklist *L)
{*L=(linklist)malloc(sizeof(LNode));
(*L)-> next=NULL;
return 1;
}
int insert (linklist L,int i,int e)
{linklist p,s;
int j=0;
p=L;
while(p&&j <i-1)
{p=p-> next;j++;}
if(!p||j> i-1)
return 0;
s=(linklist)malloc(sizeof(LNode));
s-> data=e;
s-> next=p-> next;
p-> next=s;
return 1;
}
int del(linklist L,int i,int *e)
{linklist p,q;
int j=0;
p=L;
while(p-> next&&j <i-1)
{p=p-> next;j++;}
if(!p-> next||j> i-1)
return 0;
q=p-> next;
p-> next=q-> next;
*e=q-> data;
printf( "The deleted number:%d\n\n ",*e);
free(q);
return 1;
}
void print(linklist L)
{linklist p;
for(p=L-> next;p;p=p-> next)
printf( "%4d ",p-> data);
printf( "\n ");
}
void main()
{linklist L,p;
int i,e,j,t;
t=Init(&L);
printf( "%d\n\n ",t);
for(i=1;i <=5;i++)
{scanf( "%d ",&e);
insert(L,i,e);
}
print(L);
printf( "\n ");
printf( "Enter the delete seat: ");
scanf( "%d ",&j);
printf( "\n ");
del(L,j,&e);
print(L);
printf( "\n\n ");
}
struct node{
char *name;
struct node *next;
};
struct node *Head;
Head为单向链表头,并按照其成员变量name的字符序大小排列。
分别编写函数添加和删除一个struct node类型的结点。
------解决方案--------------------
添加:逐个节点遍历,直到找到正确的插入位置。
删除:逐个节点遍历,直到找到需要删除的节点。
都是一些基本的指针操作,没什么复杂的,自己试试看。
------解决方案--------------------
//线性链表插入,删除操作
#include <stdio.h>
#include <malloc.h>
typedef struct LNode
{int data;
struct LNode *next;
}LNode,*linklist;
int Init(linklist *L)
{*L=(linklist)malloc(sizeof(LNode));
(*L)-> next=NULL;
return 1;
}
int insert (linklist L,int i,int e)
{linklist p,s;
int j=0;
p=L;
while(p&&j <i-1)
{p=p-> next;j++;}
if(!p||j> i-1)
return 0;
s=(linklist)malloc(sizeof(LNode));
s-> data=e;
s-> next=p-> next;
p-> next=s;
return 1;
}
int del(linklist L,int i,int *e)
{linklist p,q;
int j=0;
p=L;
while(p-> next&&j <i-1)
{p=p-> next;j++;}
if(!p-> next||j> i-1)
return 0;
q=p-> next;
p-> next=q-> next;
*e=q-> data;
printf( "The deleted number:%d\n\n ",*e);
free(q);
return 1;
}
void print(linklist L)
{linklist p;
for(p=L-> next;p;p=p-> next)
printf( "%4d ",p-> data);
printf( "\n ");
}
void main()
{linklist L,p;
int i,e,j,t;
t=Init(&L);
printf( "%d\n\n ",t);
for(i=1;i <=5;i++)
{scanf( "%d ",&e);
insert(L,i,e);
}
print(L);
printf( "\n ");
printf( "Enter the delete seat: ");
scanf( "%d ",&j);
printf( "\n ");
del(L,j,&e);
print(L);
printf( "\n\n ");
}