如何创建无头结点的单链表
我们常见的创建单链表都是带头节点的,这很方便,但有时候需要使用不带头节点的单链表,如何创建呢?
创建多个节点的单链表,因为刚开始表头是空的,所以需要在循环里加入判断。代码如下:
#include<iostream>
using namespace std;
typedef struct ListNode{
int data;
struct ListNode *next;
}SlistNode,*PListNode;
PListNode creatList(int n){
PListNode head;//表头指针
PListNode rear;//表为指针
PListNode temp;
head=rear=NULL;
for(int i=0;i<n;i++){
temp=new SlistNode;
temp->data=i+1;
if(head==NULL)
head=temp;//新节点插入到空表
else
rear->next=temp;//新节点插入到表尾
rear=temp;//rear指向表尾
}
if(rear!=NULL) rear->next=NULL; // 末尾结点指针域置为NULL
return head;
}