c++ 实现双向链表

双向链表:

#include<iostream>
using namespace std;

typedef struct list
{
    int data;
    struct list *front;
    struct list *next;
}List;

List *head;  //头结点
List *tail;  //尾结点
int sum = 0;

void push(int e)
{
    List *p = new List;
    p->data = e;
    if(sum == 0)
    {
        head = p;
        tail = p;
        p->front = NULL;
        p->next = NULL;
    }
    else
    {
        tail->next = p;
        p->front = tail;
        tail = p;
        p->next = NULL;
    }
    sum++;
}

void pop_back()
{
    List *p = tail->front;
    p->next = NULL;
    free(tail);
    tail = p;
}

void pop_front()
{
    List *p = head->next;
    p->front = NULL;
    delete head;
    head = p;
    
}

void Forward()
{
    List *p = head;
    while(p != NULL)
    {
        cout << p->data << " ";
        p = p->next;
    }
}

void reverse()
{
    List *p = tail;
    while(p != NULL)
    {
        cout << p->data << " ";
        p = p->front;
    }
}

int main()
{
    cout << "sdfgd" << endl;
    for(int i = 0 ; i < 9;i++)
        push(i);
    cout << "正向输出:";
    Forward();
    cout << endl << "反向输出:";
    reverse();
    cout << endl << "删除首尾结点后:" << endl;
    pop_back();
    pop_front();
    Forward();
    cout << endl;
    reverse();
    return 0;
}
// 测试
正向输出:0 1 2 3 4 5 6 7 8 
反向输出:8 7 6 5 4 3 2 1 0 
删除首尾结点后:
1 2 3 4 5 6 7 
7 6 5 4 3 2 1
//
posted @ 2019-12-08 12:34  翁德彪  阅读(360)  评论(0编辑  收藏  举报