带头节点的单链表

需要注意

# include<iostream>
# define MAXLEN 20
# define ElementType char
using namespace std;
typedef struct slNode
{
    ElementType x;
    struct slNode *next;
}node;
//=====================函数声明======================
void InitialList(node *&L);
int ListLength(node *L);
void GetElement(node *L,int i,ElementType &x);
node *ListLocate(node *L);
void ListInsert(node *&L, int i, ElementType x);
void ListDelete(node*&L, int i);

//=====================主函数========================
int main()
{
    node *L;
    InitialList(L);
    ElementType x;
    int i = 0;
    ListInsert(L, 0,4);
    ListDelete(L, 0);
    cout << "输入char型的元素,不大于20个,按\"#\"键结束" << endl;
    cin >> x;
    while (x != '#')
    {
        i++;
        ListInsert(L, i, x);
        cin >> x;
    }
    i = 0;
    for (node *s = L->next; s != NULL; s = s->next)
    {
        i++;
        cout <<"第"<<i<<"个元素为:"<<s->x << endl;
    }
     system("pause");
    return 0;
}

//========================函数定义=========================
void InitialList(node *&L)
{   
    L = new node;
    L->next = NULL; 
}
int ListLength(node *L)
{
    int i = 0;
    for (node *p = L->next; p != NULL; p = p->next)
        i++;
    return i;
}
node *GetElement(node *L, int i)
{
    int j = 1;
    node *p = L->next;
    for (; p != NULL&&i!=j; p = p->next)
    {
        j++;

    }
    if (p == NULL)
        cout << "取值序号错误" << endl;
    return p;

}
node *ListLocate(node *L,ElementType x)
{
    node *p = L->next;
    while (p->x != x&&p != NULL)
        p = p->next;
    if (p == NULL)
        cout << "没有该元素" << endl;
    return p;

}
void ListInsert(node *&L, int i, ElementType x)
{
    node *p = L;
    int j = 0;
    while (j != i-1&&p!=NULL)
    {
        p = p->next;
        j++;
    }
    if (p == NULL)
        cout << "插入序号错误" << endl;
    else
    {
        node *s = new node;
        s->x = x;
        s->next = p->next;
        p->next = s;
    }
}
void ListDelete(node*&L, int i)
{
    node *u, *p=L;
    int j = 0;
    while (j != i - 1 && p != NULL)
    {
        j++;
        p = p->next;
    }
    if (p == NULL||p->next==NULL)//最后一个节点不可删,当p指向最后一个节点时,p->next==NULL
        cout << "删除序号错误" << endl;
    else
    {
        u = p->next;
        p ->next = u->next;
        delete u;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值