单链表—不带头节点插入操作

无头节点,注意是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;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值