带头结点和不带头结点的区别
带头结点:链表的头结点不直接存储有效数据,而是在头结点的下一个才开始存储有效数据,为了方便管理,链表的头结点可以存储整条链表的结点的个数
不带头结点:从链表的头结点直接开始存储有效数据
无论带头结点和带不带头结点,链表头还是有的
创建链表及头插法插入新结点
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
int data;
struct Node *next;
};
void printfLink(struct Node *head)
{
struct Node *point = head;
while(point != NULL)
{
printf("%d->", point->data);
point = point->next;
}
printf("NULL\n");
}
struct Node *headInsert(struct Node *new, struct Node *head)
{
if(head == NULL)
{
head = new;
}
else
{
new->next = head;
head = new;
}
return head;
}
struct Node *createLink(struct Node *head, int len)
{
int i;
struct Node *new = NULL;
for(i=1;i<=len;i++)
{
new = (struct Node *)malloc(sizeof(struct Node));
memset(new, 0, sizeof(struct Node));
new->next = NULL;
scanf("%d", &(new->data));
head = headInsert(new, head);
}
return head;
}
int main()
{
struct Node *head = NULL;
head = createLink(head, 5);
printfLink(head);
return 0;
}
创建链表及尾插法插入新结点
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
int data;
struct Node *next;
};
void printfLink(struct Node *head)
{
struct Node *point = head;
while(point != NULL)
{
printf("%d->", point->data);
point = point->next;
}
printf("NULL\n");
}
struct Node *tailInsert(struct Node *new, struct Node *head)
{
struct Node *point = head