链表头节点作用
参考:
单链表头节点,头指针
深刻理解:带头结点和不带头结点的区别 使用头结点的优势
定义
头指针:链表第一个节点的存储位置
首节点:第一个存储数据的节点
头节点: 首节点前面,存放首节点地址
头节点不是链表必须的 ,但有头节点能让链表对首节点的操作,如首节点前插入节点和删除首节点和操作其他节点一样。
程序示例
sturct node;
typedef struct node *ptrtonode;
typedef ptrtonode list;
typedef ptrtonode position;
struct node {
int data;
ptrtonode next;
};
节点前插入节点
中间节点前插入
int n;
position p, pbefore;
position tem = (list)malloc(sizeof(struct node));
tem->data = n;
tem->next = p;
pbefore->next = tem;
有头节点在首节点前插入
int n;
position pfirst = L->next;//首节点
position tem = (list)malloc(sizeof(struct node));
tem->data = n;
tem->next = pfirst;
L->next = tem;
可见首节点与中间节操作一样,首节点插入时 p = L->next; pbefore = L;
无头节点在首节点前插入
int n;
position tem = (list)malloc(sizeof(struct node));
tem->data = n;
tem->next = L;
L = tem;
与中间节点操作不同,因此需要单独操作。
删除节点
中间位置删除节点
position pbefore, p;//p指向要删除的节点
pbefore->next = p->next;
free(p);
有头节点删除首节点
position pfirst = L->next;
L->next = pfirst->next;
free(pfirst);
操作与中间相同
无头节点删除首节点
position tem = L;
L = L->next;
free(tem);
需要单独判断操作