删除链表中指定位置的元素

这是一个C++程序,用于创建链表并删除指定位置的元素。程序首先通过`Greatlist`函数创建一个链表,然后使用`getPtr`函数获取要删除节点的前一个节点,接着修改指针连接以删除目标节点,并释放内存。最后,程序输出删除指定节点后的链表。
摘要由CSDN通过智能技术生成

#include<stdio.h>
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct node {
    Elemtype data;
    struct node* next;
};
node* Greatlist(int n)                       //创建链表
{
    node*p, *r, *head = NULL;
    r = (node*)malloc(sizeof(node));
    int i;
    Elemtype c;
    for (i = 1; i <= n; i++)
    {
        cin >> c;
        p = (node*)malloc(sizeof(node));
        p->data = c;
        p->next = NULL;
        if (head == NULL)
        {
            r=head= p;
        }
        else
        {
            
            r->next = p;
            r = p;
        }
    }
    return head;
}

int Linklen(node*head)                        //返回链表长度,本题中用不到这个函数
{
    int count = 0;
    node* p = head;
    while (p!=NULL)
    {
        count++;
        p=p->next;
    }
    return count;
}

node* getPtr(node* head, int pos)              //得到指定位置的链表元素的指针
{
    node* p = head;
    int i;
    for (i = 1; i < pos; i++)
    {
        p = p->next;
    }
    return p;
}

int main()
{
    node*l;
    cout << "input 10 interger:" << endl;
    l = Greatlist(10);
    cout << "the length is:" << Linklen(l) << endl;
    node*p, *q;
    p = getPtr(l, 4);
    q = p->next;
    p->next = q->next;
    free(q);
    cout << "the linklist after deleting the fifth node :" << endl;
    p = l;
    while (p)
    {
        cout << p->data << " ";
        p = p->next;
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值