双向链表

/* keep a head and end node for doubly linked list
 * Note: here wu should the end node 
 */
#include<stdio.h>
#include<stdlib.h>

typedef struct _list
{
    int _element;
    struct _list *_left, *_right;
}list_t;

list_t *insertList(list_t *head, list_t **end, int n);
void printForward(list_t *head);
void printReverse(list_t *end);

main(void)
{
	int n;
	int x;
	list_t *head = NULL;
	list_t *end = NULL;
	printf("Input number of node: ");
	scanf("%d", &n);
	while(n--)
	{
		scanf("%d", &x);
		head = insertList(head, &end, x);
	}
	printf("The list: \n");
	printForward(head);
	printReverse(end);
}

/* keep head and end node of doubly list. */
/* Note: function will return head; if we want to get the end of list, we need use "**end" as parameters
 */
list_t *insertList(list_t *head, list_t **end, int n)
{
	list_t *temp, *prev;
	
	prev = temp = head;
	if(head == NULL) //if list is empty, we put the node as head
	{
		head = (list_t *)malloc(sizeof(list_t));
		if(head == NULL)
		{
			printf("error: malloc\n");
			exit(0);
		}
		head->_element = n;
		head->_left = head->_right = NULL;
		*end = head;
	}
	else //or we input the node at the end of list
	{
		temp = (list_t*)malloc(sizeof(list_t));
		if(temp == NULL)
		{
			printf("error: malloc\n");
			exit(0);
		}
		temp->_element = n;
		temp->_left = (*end);
		temp->_right = NULL;
		(*end)->_right = temp;
		(*end) = temp;
	}
	return head;
}

/*insert a new node at the node_no order*/
list_t *insertNewNode(list_t *head, int node_no, int value)
{
	list_t *curr, *prev;
	int i;
	if(node_no <= 0 || node_no > nodecount(head))
	{
		printf("error: node does not exist\n");
		return;
	}
	if()
}


void printForward(list_t *head)
{
	printf("Elements in the list in forward order: ");
	while(head != NULL)
	{
		printf("%d ", head->_element);
		head = head->_right;
	}
	putchar('\n');
}

void printReverse(list_t *end)
{
	printf("Elements in the list in reverse order: ");
	while(end != NULL)
	{
		printf("%d ", end->_element);
		end = end->_left;
	}
	putchar('\n');
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值