单向链表的构建,大家应该不陌生
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Node)
typedef struct Node /*创建一个链式结构*/
{
int num;
struct Node*next;/*定义指针指向下一元素*/
}Tree;
void CreatList()
{
Tree*head,*p1,*p2;/*一定要单独定义一个指针,作为链表的头*/
int i,n;
head=NULL; /*建立一个空的链表*/
scanf("%d",&n); /*输入链表包含几个元素*/
for(i=1;i<=n;i++)
{
p1=(Tree*)malloc(LEN);/*动态申请内存进行链表的构建*/
scanf("%d",&p1->num);
if(i==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
p2->next=NULL;/*最后以NULL作为链表的结束*/
/*Ps:如果这里是 p2->next=head 那么这就是一个循环链表*/
}
双向链表其实也一个道理
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct node)
using namespace std;
typedef struct node /*创建一个结构*/
{
int data;
node *prior,*next; /*用2个指针一个指向前方元素一个指向后方元素,构成双向链表*/
}List;
List *p,*q,*head;
void CreatList(int n) /*创建一个双向链表*/
{
head=(List*)malloc(LEN); /*申请内存空间*/
head->data=0;
p=head;
for(int i=0;i<n;i++)
{
q=(List*)malloc(LEN);
printf("请输入第%d/%d个元素:",i+1,n);
scanf("%d",&q->data);
p->next=q; /*将p的下一个元素指向新申请到的内存,构成链式结构*/
q->next=head; /*时刻使得最后的链尾指向开头,构成环状结构*/
q->prior=p; /*构成双向链表*/
p=q; /*移动节点继续链接*/
}
head->prior=p;
}
void print()
{
p=head->next;
printf("正向输出顺序为:\n");
while(p!=head)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
p=head->prior;
printf("逆向输出顺序为:\n");
while(p!=head)
{
printf("%d ",p->data);
p=p->prior;
}
}
int main()
{
int n;
scanf("%d",&n);
CreatList(n);
print();
return 0;
}