/* 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');
}
双向链表
最新推荐文章于 2024-04-16 22:43:46 发布