链表可以没有头结点,但是不能没有头指针.
单链表中第一个结点的存储位置叫做头指针,最后一个结点的指针域为空,但是有数据域.整个链表的存取从头指针开始.如果链表有头结点,那么头指针就是指向头结点数据域的指针,如下图所示:

没有头结点的单链表如下所示;

**
注意:
**
①头结点是为了操作方便和统一设立的,它的数据域一般无意义(存储链表一些信息).
②无论链表是否为空,头指针都不为空.
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
**//尾插法构建不带头结点的单链表**
struct node * creat_wf(int n)
{
struct node *head;
struct node *p,*q;
head = NULL;
for(int i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
if(head == NULL)
head = p;
else
q->next = p;
q=p;
}
q->next = NULL;
return head;
}
**//尾插法构建带头结点的单链表**
struct node * creat_wt(int n)
{
struct node *head;
struct node *p,*q;//尾插法中必须有一个尾指针始终指向当前链表的尾结点
//创建头结点
**//****头结点的作用:①在链表第一个位置上的操作和其他位置一样,不需要进行特殊处理 ②无论链表是否为空,其头指针都是指向头结点的非空指针,因此空表和非空表的处理统一**
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
head=p;
//构建其他结点
for(int i=1;i<n;i++)
{
q=(struct node *)malloc(sizeof(struct node));
cin>>q->data;
p->next = q;
p=q;
}
p->next = NULL;
return head;
}
**//头插法构建单链表**
struct node * creat_t(int n)
{
struct node *head;
struct node *p;
head=NULL;
for(int i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));//生成新的结点
cin>>p->data;
p->next=head;
head=p;
}
return head;
}
**//输出链表**
void out_l(struct node *head)
{
struct node *h=head;
while(h)
{
cout<<h->data<<endl;
h=h->next;
}
}
int main()
{
int n;
cin>>n;
struct node *head=creat_wt(n);
out_l(head);
struct node *head1=creat_t(n);
out_l(head1);
struct node *head2=creat_wt(n);
out_l(head2);
return 0;
}
动态创建链表并且进行测试:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
};
int main()
{
struct ListNode *head;
struct ListNode *p,*q;
head=NULL;
int n;
while(cin>>n)//输入一串字符后,回车换行符也被存在缓冲区
{
p = (struct ListNode *) malloc(sizeof(struct ListNode));
p->val=n;
if (head == NULL)
head = p;
else
q->next = p;
q = p;
if(cin.get()=='\n')//判断缓冲区是否为回车符
break;
}
q->next=NULL;
while(head) {
cout << head->val << endl;
head = head->next;
}
}