题目
拟采用带头结点的单链表来存储线性表中的数据元素,但要求单链表中数据元素的存储顺序与线性表中数据元素的顺序逆序。即若线性表中的数据元素序列是a1,a2,……, an-1,an,则实现的单链表的数据元素的序列是an,an-1, ……,a2,a1(请见图2)。
广告
若有同学需要桂林电子科技大学数据结构考研真题和答案解析(个人制作)或指定参考书《算法与数据结构》第三版张乃孝PDF等资料的欢迎交流(QQ((肆+壹)幺幺)&微信(月球不太圆)15577498906)
算法思路
采用头插法建立链表即可。函数需要参数n,输入n个数字后退出循环。
代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
LinkList list_headinsert(int n,LinkList L)
{
LNode *s;
int x;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
cin>>x;
while(n!=0)
{
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
n=n-1;
if(n!=0)
cin>>x;
}
return L;
}
int main(int argc, char** argv) {
LinkList L=NULL;
LinkList s=NULL;
int n;
cout<<"请输入n的值"<<endl;
cin>>n;
s=list_headinsert(n,L);
if(s!=NULL)
s=s->next;
else
cout<<"s is null"<<endl;
while(s!=NULL)
{
cout<<s->data<<" ";
s=s->next;
}
cout<<endl;
cout<<"sadf"<<endl;
if(L!=NULL)
{
L=L->next;
}
else
cout<<"L is null"<<endl;
while(L!=NULL)
{
cout<<L->data<<" ";
L=L->next;
}
return 0;
}