|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}node;
void CreateList(node *L,int n)
{
node *s,*r;
int i;
srand(time(NULL));
L=(node *)malloc(sizeof(node));
r=L;
for(i=0;i<n;i++)
{
s=(node *)malloc(sizeof(node));
s->data=rand()%101;
r->next=s;
r=s;
}
}
bool InsertList(node *L,int i,ElemType e)
{
node *s;
node *p;
int j=0;
s=L;
while(j<i-1 && s!=NULL)
{
s=s->next;
j++;
}
if(s==NULL)
return false;
else
{
p=(node *)malloc(sizeof(node));
p->data=e;
p->next=s->next;
s->next=p;
return true;
}
}
bool DelList(node *L,int i)
{
ElemType a;
node *p,*r;
int j=0;
p=L;
while(j<i-1 && p!=NULL)
{
p=p->next;
j++;
}
if(p==NULL)
return false;
else
{
p->next=r;
a=r->data;
p->next=r->next;
free(r);
return true;
}
}
int ListLength(node *L)
{
int n=0;
node *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return (n);
}
main()
{
node L;
ElemType c;
int Len;
int i;
CreateList(&L,10);
printf("请输入要插入的元素:");
for(i=0;i<10;i++)
{
scanf("%d\n",&c);
InsertList(&L,4,c);
}
Len=ListLength(&L);
for(i=0;i<Len;i++)
{
printf("此时链表的元素有:%d",L.data);
}
DelList(&L,3);
Len=ListLength(&L);
for(i=0;i<Len;i++)
{
printf("此时链表的元素有:%d",L.data);
}
}
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}node;
void CreateList(node *L, int n)
{
node *s, *r;
int i;
srand((unsigned int)time(NULL));
//L = (node *)malloc(sizeof(node));
r = L;
for (i = 0; i < n; i++)
{
s = (node *)malloc(sizeof(node));
s->data = rand() % 100;
s->next = NULL;
r->next = s;
r = s;
}
}
bool InsertList(node *L, int i, ElemType e)
{
node *s;
node *p;
int j = 0;
s = L;
while (j < i - 1 && s != NULL)
{
s = s->next;
j++;
}
if (s == NULL)
return false;
else
{
p = (node *)malloc(sizeof(node));
p->data = e;
p->next = s->next;
s->next = p;
return true;
}
}
bool DelList(node *L, int i)
{
ElemType a;
node *p, *r;
int j = 0;
p = L;
while (j < i - 1 && p != NULL)
{
p = p->next;
j++;
}
if (p == NULL)
return false;
else
{
r = p->next;
//p->next = r;
a = r->data;
p->next = r->next;
free(r);
return true;
}
}
int ListLength(node *L)
{
int n = 0;
node *p = L;
while (p->next != NULL)
{
n++;
p = p->next;
}
return (n);
}
void Show(node *T, int Len)
{
for (int i = 0; i < Len; i++)
{
T = T->next;
printf("此时链表的元素有:%d\n", T->data);
}
}
void main()
{
node L;
ElemType c;
int Len;
CreateList(&L, 10);
Len = ListLength(&L);
Show(&L, Len);
printf("请输入要插入的元素:");
scanf("%d", &c);//3
InsertList(&L, 4, c);
Show(&L,Len);
DelList(&L, 3);
Show(&L, Len);
}
调试环境:Visual Studio 2013
|
|