概述
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node {
int data;
struct Node* next, * pre;
}Node;
typedef struct DList {
Node head;
int length;
}DList;
Node* getNewNode(int val) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = val;
p->next = p->pre = NULL;
return p;
}
DList* init_list() {
DList* l = (DList*)malloc(sizeof(DList));
l->head.next = NULL;
l->length = 0;
return l;
}
int insert(DList* l, int ind, int val) {
if (l == NULL) return 0;
if (ind < 0 || ind > l->length) return 0;
Node* p = &(l->head), * node = getNewNode(val);
while (ind--) p = p->next;
node->next = p->next;
p->next = node;
node->pre = p;
if (node->next != NULL) node->next->pre = node;
l->length += 1;
return 1;
}
void l_output(DList* l) {
if (l == NULL) return;
printf("l_output(%d) : ", l->length);
for (Node* p = l->head.next; p; p = p->next) {
printf("%d->", p->data);
}
printf("NULLn");
return;
}
void r_output(DList* l) {
if (l == NULL) return;
printf("r_output(%d) : ", l->length);
int ind = l->length;
Node* p = &(l->head);
while (ind--)
p = p->next;
for (; p != &(l->head); p = p->pre) {
printf("%d->", p->data);
}
printf("headn");
return;
}
int erase(DList* l, int ind) {
if (l == NULL) return 0;
if (ind < 0 || ind >= l->length) return 0;
Node* p = &(l->head), * q;
while (ind--) p = p->next;
q = p->next;
p->next = q->next;
if (q->next != NULL) q->next->pre = p;
free(q);
l->length -= 1;
return 1;
}
void clear(DList* l) {
if (l == NULL) return;
Node* p = l->head.next, * q;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
free(l);
return;
}
int main() {
srand(time(0));
#define MAX_OP 20
DList* l = init_list();
for (int i = 0; i < MAX_OP; i++) {
int op, ind, val;
op = rand() % 4;
ind = rand() % (l->length + 3) - 1;
val = rand() % 100;
switch (op) {
case 0:
case 1:
case 2:
printf("insert %d at %d to list
= %dn", val, ind, insert(l, ind, val));
break;
case 3:
printf("erase a item at %d from list = %dn", ind, erase(l, ind));
}
l_output(l);
r_output(l);
}
return 0;
}
最后
以上就是尊敬小伙为你收集整理的双向链表遍历的全部内容,希望文章能够帮你解决双向链表遍历所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复