双向链表 代码



#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
 struct node *prev;
 struct node *next;
 int value;
} Node;

class linked_list
{
private:
 Node * head;
 Node * cur;

public:
 linked_list();
 ~linked_list();

 int push(int data);
 int pop(int& data);
 int display(void);
};

linked_list::linked_list()
{
 head = NULL;
 cur = NULL;
}

linked_list::~linked_list()
{
}

int linked_list::push( int data)
{
 Node *tmp = NULL;
 tmp = (Node *) malloc(sizeof(Node));
 if (NULL == tmp)
 {
  return -1;
 }
 else
 {
  tmp->value = data;
  tmp->next = NULL;
  tmp->prev = NULL;
 }

 if (NULL == head)
 {
  head = tmp;
 }
 else
 {
  head->prev = tmp;
  tmp->next = head;
  head = tmp;
 }
 return 0;
}

int linked_list::pop( int& data )
{
 Node *tmp = NULL;

 if (NULL == head)
 {
  printf(“empty linked list, have no value to be poped\n”);
  return -1;
 }
 data = head->value;
 tmp = head;
 head = head->next;
 if (NULL != head)
 {
  head->prev = NULL;
 }
 free(tmp);

 return 0;
}

int linked_list::display()
{
 int number = 0,data=0;
 int i = 0;

 printf(“please input the number of test value:”);
 scanf(“%d”, &number);
 for (int i = 0; i < number; i++)
 {
  printf(“\ndata[%d]=”,i);
  scanf(“%d”,&data);
  push(data);
 }
 printf(“the poped datas are:\n”);
 for(; i < number; i++)
 {
  pop(data);
  printf(“%d “,data);
 }
 return 0;
}

int main(void)
{
 linked_list list;

 list.display();
}

点赞