1:概念:
单向链表是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。链表是使用指 针进行构造的列表,并且是由一个个结点组装起来的,因此又称为结点列表。其中每个结点都有指针成员变量指向列表中的下一个结点,head指针指向第一个结点称为表头,而终止于最后一个指向nuLL的指针。
2:图示
3:代码示例
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*带有头节点的单向链表*/
typedef struct Node
{
int id; //数据域
Node *next; //指针域
}Node;
/*创建头节点*/
Node * CreateList()
{
//头节点作为标志,不存储有效数据
Node * head = NULL;
head = (Node *)malloc(sizeof(Node));
if (head == NULL)
{
return NULL;
}
head->id = -1;
head->next = NULL;
Node * pCur = head;
Node * pNew = NULL;
int data;
while (1)
{
printf("please input data:\n");
scanf("%d", &data);
if (data == -1)
{
break;
}
//新节点动态分配内存空间
pNew = (Node *)malloc(sizeof(Node));
if (pNew==NULL)
{
break;
}
//新节点成员变量赋值
pNew->id = data;
//pNew->next = NULL;
//链表建立关系
pCur->next = pNew; //当前节点的next指向pNew
pNew->next = NULL; //pNew的下一个节点指向NULL
pCur = pNew; //把pCur的位置移动到pNew
}
return head;
}
//在值为x的结点前,插入值为y的结点;若值为x的结点不存在,则插在表尾。
int insertList(Node *head,int x,int y)
{
if (head == NULL)
{
return -2;
}
Node *pPre = head;
Node *pCur = head->next;
while (pCur != NULL)
{
if (pCur->id == x)
{
break;
}
pPre = pCur; //pPre指向pCur位置
pCur = pCur->next; //pCur指向下一个结点
}
/*2种情况
*1. 找匹配的结点,pCur为匹配结点,pPre为pCur上一个结点
*2. 没有找到匹配结点,pCur为空结点,pPre为最后一个结点
*/
Node *pNew = (Node *)malloc(sizeof(Node));
if (pNew == NULL)
{
return -3;
}
pNew->id = y;
pNew->next = NULL;
pPre->next = pNew; //pPre下一个指向pNew
pNew->next = pCur; //pNew下一个指向pCur
return 0;
}
/*删除给定值的节点*/
int deleteList(Node *head, int x)
{
if (head == NULL)
{
return -1;
}
Node *pPre = head;
Node *pCur = head->next;
while (pCur != NULL)
{
if (pCur->id == x)
{
pPre->next = pCur->next;
free(pCur);
pCur = NULL;
break;
}
pPre = pCur;
pCur = pCur->next;
}
return 0;
}
/*清空链表*/
int destroyList(Node *head)
{
if (head ==NULL)
{
return -1;
}
Node *tmp = NULL;
int i = 0;
while (head != NULL)
{
tmp = head->next;
free(head);
head = NULL;
head = tmp;
i++;
}
printf("i=%d\n", i);
return 0;
}
/*链表遍历*/
int PrintList(Node *head)
{
if (head == NULL)
{
return -1;
}
Node *pCur = head->next;
printf("head->");
while (pCur != NULL)
{
printf("%d -> ", pCur->id);
pCur = pCur->next;
}
printf("NULL\n");
return 0;
}
int main()
{
Node *head = NULL;
head = CreateList();
PrintList(head);
insertList(head, 5, 12);
PrintList(head);
deleteList(head, 6);
PrintList(head);
destroyList(head);
system("pause");
return 0;
}