双向链表加数

来源:互联网 发布:无锡网络开发有限公司 编辑:程序博客网 时间:2024/05/22 23:18

ps:可能有错,请大佬指出。不考虑插头和插尾的情况。

附丑图一张

#include <iostream>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node
{
    int data;
    struct node *pre;//前指针
    struct node *next;//后指针
};
int main()
{
    struct node *p,*t,*head,*q,*flag;
    int n,a;
    while(cin>>n)//输入N个数
    {
          head=NULL;//地址为空
        for(int i=1;i<=n;i++)
        {
            cin>>a;//输入一个数字
            p=(struct node *)malloc(sizeof(struct node));//开辟一个新空间
            p->data=a;//把输入的数存起来
            p->next=NULL;//存在的意义:当输入完最后一个数字后,他的后指针为空
            p->pre=NULL;//同理,输入第一个数字时,他的前指针为空
            if(head==NULL)
                head=p;
            else
            {
                p->pre=q;//新开辟的空间的前指针指向上一个地址
                q->next=p;//上一个地址的后指针指向新开辟的空间
            }
            q=p;
        }
        int local,test=0;
        cin>>local>>a;//输入想要插入的位置,和数
        p=(struct node*)malloc(sizeof(struct node));
        p->data=a;
        p->next=NULL;
        p->pre=NULL;
        t=head;
        while(t!=NULL)//从头开始遍历
        {
            test++;
            if(test==local-1)
            {
                p->next=t->next;//把新开辟空间的后指针指向你想要插入位置的地址
                t->next->pre=p;//将你想要插入的位置的前指针指向新开辟的空间
                t->next=p;//将你想要插入的前一个位置的后指针指向现在开辟的空间
                p->pre=t;//将新开辟空间的前指针指向插入的前一个位置;
                break;
            }
            t=t->next;
        }
        t=head;//从头开始遍历
        while(t!=NULL)
        {
            cout<<t->data<<" ";
            if(t->next==NULL)//到最后一个数字时,用falg记录地址
                flag=t;
            t=t->next;
        }
        cout<<endl;
        t=flag;//从尾开始遍历
        while(t!=NULL)
        {
            cout<<t->data<<" ";
            t=t->pre;
        }
        cout<<endl;
    }
    return 0;
}
0 0