链表插入删除

#include <iostream.h>
#include <stdlib.h>

typedef struct Node
{
    char data;
    struct Node *next;
}Node, *LinkList;

void CreateList(LinkList &head)  //创建链表
{
    Node *s, *p;
    char data;

    head = (Node *)malloc(sizeof(Node));
    head->next = NULL;

    p = head;
    while(1)
    {
        cout << "请输入data:(q退出)" << endl;
        cin >> data;

        if(data == 'q')
        {
            break;
        }

        s = (Node *)malloc(sizeof(Node));
        s->next = NULL;
        s->data = data;
       
        p->next = s;
        p = s;
    }
}

int DeleList(LinkList &head, int i, char *e)  //删除第i个节点,并把节点的值用e返回
{
    Node *p, *q;
   
    p = head->next;

    int j = 1;

    while(p && j < i-1)
    {
        p = p->next;
        j++;
    }
   
    if(!p || j > i-1)
    {
        return -1;
    }

    q = p->next;
    p->next = q->next;
    *e = q->data;
   
    free(q);
    return 1;
}

void display(Node *head)
{
    Node *p;
    p = head->next;

    while(p != NULL)
    {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}

int InsertList(LinkList &head, int i, char e)  // 在第i个位置插入值为e的一个新节点
{
    LinkList p, s;
    int j = 1;

    p = head;
    while(p && j < i)
    {
        p = p->next;
        j++;
    }

    if(!p || j > i)
    {
        cout << "i的位置不存在" << endl;
        return -1;
    }

    s = (LinkList)malloc(sizeof(Node));
    s->data = e;

    s->next = p->next;
    p->next = s;

    return 1;
}

int main()
{
    LinkList head;
    char e;
   
    CreateList(head);
    display(head);

    DeleList(head, 3, &e);
    display(head);

    InsertList(head,5,'m');
    display(head);
    return 1;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值