-
建立单链表的两种方法:
(要注意理解输出截止条件!!!)
头插法和尾插法:
#include<iostream>
#include<cstring>
using namespace std;
typedef struct Node
{
int num;
char arr[100];
struct Node *next;
}node;
//头插法输出的截止条件是因为头节点的数据域不存值
//尾插法的输出截止条件是因为尾结点的数据域存值
int main()
{
//尾插法:
int num;
node *s,*r,*head;
head=(node*)malloc(sizeof(node));
head->next=NULL;
s=head;
for(int i=1;i<=5;i++)
{
cin>>num;
node *p=(node*)malloc(sizeof(node));
p->num=num;
s->next=p;
p->next=NULL;
s=p;
}
s=head->next;
while(s!=NULL)//注意输出截至条件!
{
cout<<s->num<<" ";
s=s->next;
}
return 0;
//头插法
int num;
node *head,*s;
head=(node*)malloc(sizeof(node));
head->next=NULL;
s=head;
for(int i=1;i<=5;i++)
{
cin>>num;
node*p=(node*)malloc(sizeof(node));
p->num=num;
p->next=s;
s=p;
}
while(s->next!=NULL)//注意输出截至条件
{
cout<<s->num<<" ";
s=s->next;
}
return 0;
}