单链表—不带头节点插入操作
程序员文章站
2024-03-21 14:45:40
...
无头节点,注意是P=L,不是P=L->next
#include <iostream>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
using namespace std;
typedef struct lnode{
int data;
struct lnode *next;
}lnode,*linklist;
bool initlist(linklist &l) //初始化
{
l=NULL;
return TRUE;
}
bool listinsert(linklist &l,int i,int e) //不带头节点插入
{
if(i<1)
return FALSE;
if(i==1) //等于1时特殊讨论
{
lnode *s=(lnode *)malloc(sizeof(lnode));
s->data=e;
s->next=l;
l=s;
return TRUE;
}
lnode *p;
int j=1; //与带头节点不同
p=l;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL)
return FALSE;
lnode *s=(lnode *)malloc(sizeof(lnode));
s->data=e;
s->next=p->next;
p->next=s;
return TRUE;
}
int listlength(linklist l) //判断表长
{
lnode *p;
int i=0;
p=l;
while(p!=NULL)
{
cout<<p->data<<endl;
i++;
p=p->next;
}
return i;
}
int getelem(linklist l,int i) //按位查找
{
lnode *p;
int j=0;
p=l;
while(p->next!=NULL&&j<i)
{
p=p->next;
j++;
}
if(j==i)
return p->data;
else return -1;
}
lnode* locatelem(linklist l,int e) //按值查找
{
lnode *p;
p=l;
while(p!=NULL && p->data!=e)
{
p=p->next;
}
return p;
}
int main() {
linklist l;
if(initlist(l))
cout<<"initlist success-------";
if(listinsert(l,1,3))
cout<<"insert first number succeed ";
if(listinsert(l,2,7))
cout<<"insert secnod number succeed ";
if(listinsert(l,3,9))
cout<<"insert third number succeed"<<endl;
cout<<"length :"<<listlength(l)<<endl;
cout<<"local 1 :"<<locatelem(l,3)<<endl;
cout<<"local 2 :"<<locatelem(l,7)<<endl;
cout<<"local 3 :"<<locatelem(l,9)<<endl;
cout<<"first number is "<<getelem(l,0)<<endl;
cout<<"secnod number is "<<getelem(l,1)<<endl;
cout<<"third number is "<<getelem(l,2)<<endl;
cout << "over\n";
return 0;
}
上一篇: 生成子集
下一篇: 生成pdf文档 插入签名图片