#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;
}
个人版双向链表的操作
最新推荐文章于 2024-07-05 16:25:36 发布