双向链表遍历

#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("NULL\n");
	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("head\n");
	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  = %d\n", val, ind, insert(l, ind, val));
			break;
		case 3:
			printf("erase a item at %d from list = %d\n", ind, erase(l, ind));
		}
		l_output(l);
		r_output(l);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yitahutu79

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值