C/C++数据结构与算法笔记2(双向链表)
基本函数笔记来自CSDN课程 C/C++ 数据结构与算法 (王桂林)
拓展部分为自己编写 (C语言),仅供参考!
基本函数
创建链表,插入元素,遍历元素
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "list.h"
#infndef _LIST_H_
#define _LIST_H_
typedef struct _DNode
{
int data;
struct _DNode * next; //left 后继
struct _DNode * pre; //right 前驱
}DNode;
DNode * head = createList() //创建双向链表
{
DNode *head = (DNode*)malloc(sizeof(DNode));
head - > next = head ->pre = head; //循环指向自己
return head;
}
void insertList(DNode * head, int data) //插入元素
{
DNode * cur = (DNode*)malloc(sizeof(DNode));
cur->data = data;
cur->next = head->next;
cur->pre = head;
head->next = cur;
cur->next->pre = cur;
}
void traverseList(DNode *head) //遍历
{
DNode *t = head ->next; //注意防止无限循环,加标记
while(t != head)
{
printf("%2d",t->data);
t = t->next; //逆向遍历 取t = t->pre
}
}
int main()
{
DNode *head = createList();
Node * head = createList(); //创建
travereList(head);
strand(time(NULL));
for(int i=0;I<10;i++)
{
insertList(head, rand()%100) ; //插入
}
traverseList(head); //遍历
return 0;
}
拓展部分:
取链表长度,删除元素,排序,逆序,删除链表
待完成...