关于单链表的创建,分别用头插法和尾插法创建单链表
#include<stdio.h>
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef int ElemType;
typedef struct LNode{
ElemType data; //存放元素值
struct LNode *next; //指针域指向后继结点
}
ListNode;
//头插法建表
void CreateListHead(ListNode *&head,ElemType a[],int n)
{
ListNode *s;
head=(ListNode *)malloc(sizeof(ListNode));//创建头结点
head->next = NULL; //将头节点next域置空
for(int i=0;i<n;i++) //循环建立数据结点
{
//创建数据结点 *s
s=(ListNode *)malloc(sizeof(ListNode));
//将结点s插在原开始结点之前,头结点之后
s->data=a[i];
s->next=head->next;
head->next=s;
}
}
//尾插法建表
void CreateListTail(ListNode *&head,ElemType a[],int n)
{
ListNode *s,*r;
head=(ListNode *)malloc(sizeof(ListNode));//创建头结点
head->next=NULL;//将头结点next域置空
r=head;//r始终指向尾结点,开始时头结点和尾结点是同一个
for(int i=0;i<n;i++)
{
s=(ListNode *)malloc(sizeof(ListNode));//创建数据结点
s->data=a[i];//数据域
r->next=s;//将s插入到r后
r=s;//使r指向尾结点
}
r->next=NULL;//尾指针指针域置空
}
//输出
void DispList(ListNode *head)
{
ListNode *p=head->next; //p指向开始结点
while(p!=NULL)
{
cout<<p->data<<" ";//输出数据域
p=p->next;
}
cout<<endl;
}
int main()
{
ListNode *head;
int n;
cout<<"n:";
std::cin>>n;
int *a=new int (n);
for(int i=0;i<n;i++)
{
std::cin>>a[i];
}
//头插法建表
CreateListHead(head,a,n);
cout<<"头插法建表:";
DispList(head);//输出
//尾插法建表
CreateListTail(head,a,n);
cout<<"尾插法建表:";
DispList(head);//输出
return 0;
}
最后,感谢观看!^ _ ^