双向链表操作:建立,初始化,遍历,清空
双向链表常见操作如下:建立链表,初始化链表,遍历链表,清空链表,销毁链表,插入节点,删除节点,查找某节点等。
////2021年3月10日17点35分
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int node_data;
struct Node *prev;
struct Node *next;
}pNode;
struct Node *InitList(pNode *head,int n);
void TraversalList(pNode *head);
void DeleteList(pNode *head);
int ClearList(pNode *head);
////链表的各项操作
int main(void)
{
int n = 4;
pNode *head = NULL;
pNode *tail = NULL;
head = (pNode *)malloc(sizeof(pNode));
// printf("head addr: %p\n",head);
//初始化链表并赋值,返回尾节点last
tail = InitList(head,n);
// printf("head addr: %p\n",head);
// printf("tail addr: %p\n",tail);
//打印为第一个元素和最后一个元素
// printf("%d %d \n", head->next->node_data, tail->node_data);
printf("Please traversal all element of the list:\n");
TraversalList(head);
// DeleteList(head);
ClearList(head);
printf("\nPlease traversal all element of the list:\n");
TraversalList(head);
return 0;
}
////链表建立及初始化
struct Node *InitList(pNode *head,int n)
{
int i = 0;
pNode *p = NULL;
pNode *q = NULL;
p = (pNode *)malloc(sizeof(pNode));
if((NULL == p))
{
printf("内存空间已满\n:");
exit(0);
}
p = head;
p ->node_data = 0;
p ->prev = NULL;
p ->next = NULL;
////链表初始化并赋值
for(i=0;i<n;i++)
{
q = (pNode *)malloc(sizeof(pNode));
if((NULL == q))
{
printf("内存空间已满\n:");
exit(0);
}
q ->node_data = i+1;
q ->prev = p;
q ->next = NULL;
p ->next = q;
p = q; //指向尾节点
// printf("当前节点序号为 %dth\n",i+1);
// printf("当前节点数值为 %d\n", p ->node_data);
}
// free(p);
// free(q);
return p;
}
////遍历链表
void TraversalList(pNode *head)
{
int j = 0;
while(NULL != (head))
{
printf("当前节点数序号为: %d\n", j);
printf("当前节点数值为: %d\n", head ->node_data);
head = head ->next;
j++;
}
}
////销毁链表 —— 头节点也删除
void DeleteList(pNode *head)
{
pNode *p = NULL;
p = (pNode *)malloc(sizeof(pNode));
if((NULL == p))
{
printf("内存空间已满\n:");
exit(0);
}
if(NULL == head)
{
exit(0);
}
while(NULL != (head))
{
p = head ->next;
free(head);
head = p;
}
}
////清空链表 —— 保留头节点
int ClearList(pNode *head)
{
pNode *p,*q;
if(head==NULL)
{
return 0;
}
p=head->next;
while(p!=NULL)
{
q=p->next;
free(p);
p=q;
}
head->next=NULL;
return 1;
}