个人版双向链表的操作

#include <iostream>
#include <cstdio>
#include <assert.h>
#include <malloc.h>
using namespace std;
typedef struct node
{
    int data;
    struct node *pre,*next;
}LNode,*ListNode;

void InIt(ListNode list)
{
    assert(list!=NULL);
    list->next=NULL;
    list->pre=NULL;
    list->data=0;
    return;
}

bool InsertNode(ListNode p,ListNode q)
{
    assert(p!=NULL&&q!=NULL);
    q->next=p->next;
    q->pre=p;
    p->next=q;
    q->next->pre=q;
    return true;
}

bool InsertlLastNode(ListNode list,ListNode p)
{
    assert(NULL!=list&&NULL!=p);
    ListNode r=list;
    ListNode cp=list->next;
    while(cp!=NULL)
    {
        r=cp;
        cp=cp->next;
    }
    r->next=p;
    p->pre=r;
    return true;
}

bool DeleteNode(ListNode q)
{
    assert(q!=NULL);
    q->pre->next=q->next;
    q->next->pre=q->pre;
    free(q);
    return true;
}

bool findNode(const ListNode list,ListNode p)
{
    assert(NULL!=list&&NULL!=p);
    ListNode cp=list->next;
    while(cp!=NULL)
    {
        if(cp->data==p->data)
        {
            return true;
            break;
        }
    }
    return false;
}

ListNode findKNode(int k,const ListNode list)
{
    assert(k>0&&list!=NULL);
    ListNode cp=list->next;
    while(k-->1)
    {
        if(cp==NULL)
            return NULL;
        else
        {
            cp=cp->next;
        }
    }
    return cp;
}

ListNode PrintList(ListNode list)
{
    assert(list!=NULL);
    ListNode cp=list->next;
    while(cp!=NULL)
    {
        printf("%d ",cp->data);
        cp=cp->next;
    }
    printf("\n");
}

int main()
{
    ListNode list=(ListNode)malloc(sizeof(LNode));
    InIt(list);
    for(int i=0;i<10;i++)
    {
        ListNode tmp=(ListNode)malloc(sizeof(LNode));
        tmp->data=i;
        tmp->pre=tmp->next=NULL;
        InsertlLastNode(list,tmp);
    }
    PrintList(list);
    int k;
    cin>>k;
    ListNode KthNode=findKNode(k,list);
    if(KthNode!=NULL)
    {
        ListNode t=(ListNode)malloc(sizeof(LNode));
        t->data=100;
        t->pre=t->next=NULL;
        InsertNode(KthNode,t);
    }
    else
    {
        cout<<" I wrong !"<<endl;
    }

    PrintList(list);

    int t;
    cin>>t;
    ListNode tthNode=findKNode(t,list);
    if(tthNode!=NULL)
       DeleteNode(tthNode);
    else
        cout<<" d wrong !"<<endl;
    PrintList(list);
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值