基于链式存储结构的线性表的实现球代码求代码啊啊啊啊
参考如下:
C++代码:
#include <iostream>
using namespace std;
struct StNode
{
int data;
struct StNode* next;
};
//创建线性表
struct StNode* CreateList()
{
int i,n;
struct StNode* head,*p,*t;
head = (struct StNode*)malloc(sizeof(StNode));
head->next = NULL;
t = head;
cout <<"请输入链表的长度:";
cin >> n;
cout <<"请输入链表数据:";
for (i=0;i<n;i++)
{
p = new StNode;//(struct StNode*)malloc(sizeof(StNode));
cin >> p->data;//scanf("%d",&(p->data));
p->next = NULL;
t->next = p;
t = p;
}
return head;
}
//插入
struct StNode* InsertList(struct StNode*head,int pos,int data)
{
struct StNode* p = head,*t;
int i=1;
while(i<pos && p)
{
p = p->next;
i++;
}
if (p)
{
t = (struct StNode*)malloc(sizeof(StNode));
t->data = data;
t->next = p->next;
p->next = t;
cout << "插入成功\n";
}else
cout <<"插入位置不合适,插入失败\n";
return head;
}
//显示
void show(struct StNode* head)
{
struct StNode* p = head->next;
while(p)
{
cout << p->data<<" ";//printf("%d ",p->data);
p = p->next;
}
cout << endl;
//printf("\n");
}
//释放空间
void Free(struct StNode* head)
{
struct StNode* p;
while(head)
{
p = head->next;
free(head);
head = p;
}
head = 0;
}
int main()
{
int pos,data;
struct StNode* head = CreateList();
show(head);
//插入
cout << "请输入插入位置(从1开始)和数据:";
cin >> pos >> data;
head = InsertList(head,pos,data);
cout <<"插入后链表数据:";
show(head);
//释放空间
Free(head);
return 0;
}
C代码:
#include <stdio.h>
#include <stdlib.h>
struct StNode
{
int data;
struct StNode* next;
};
//创建线性表
struct StNode* CreateList()
{
int i,n;
struct StNode* head,*p,*t;
head = (struct StNode*)malloc(sizeof(StNode));
head->next = NULL;
t = head;
printf("请输入链表的长度:");
scanf("%d",&n);
printf("请输入链表数据:");
for (i=0;i<n;i++)
{
p = (struct StNode*)malloc(sizeof(StNode));
scanf("%d",&(p->data));
p->next = NULL;
t->next = p;
t = p;
}
return head;
}
//插入
struct StNode* InsertList(struct StNode*head,int pos,int data)
{
struct StNode* p = head,*t;
int i=1;
while(i<pos && p)
{
p = p->next;
i++;
}
if (p)
{
t = (struct StNode*)malloc(sizeof(StNode));
t->data = data;
t->next = p->next;
p->next = t;
printf("插入成功\n");
}else
printf("插入位置不合适,插入失败\n");
return head;
}
//删除
struct StNode* Delete(struct StNode* head,int pos)
{
int i = 1;
struct StNode* p = head,*t;
while(i<pos && p)
{
p = p->next;
i++;
}
if (p)
{
t = p->next;
p->next = t->next;
free(t);
t = 0;
printf("删除成功\n");
}else
printf("删除成功\n");
return head;
}
//显示
void show(struct StNode* head)
{
struct StNode* p = head->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
//释放空间
void Free(struct StNode* head)
{
struct StNode* p;
while(head)
{
p = head->next;
free(head);
head = p;
}
head = 0;
}
int main()
{
int pos,data;
struct StNode* head = CreateList();
show(head);
//插入
printf("请输入插入位置(从1开始)和数据:");
scanf("%d %d",&pos,&data);
head = InsertList(head,pos,data);
printf("插入后链表数据:");
show(head);
//删除
printf("请输入删除位置(从1开始):");
scanf("%d",&pos);
head = Delete(head,pos);
printf("删除后链表数据:");
show(head);
//释放空间
Free(head);
return 0;
}