单链表的删除操作的实现

建立长度为n的单链表,删除第i个结点之前的结点。
Description
第一行为自然数n,表示链式线性表的长度; 
第二行为n个自然数表示链式线性表各元素值; 
第三行为指定的删除参数i。 
Input
指定删除位置合法时候,输出删除元素后的链式线性表的所有元素,元素之间用一个空格隔开。 
输入不合法,输出"error!"。
Output
1
2
3
4
5
1 2 3 4 5
3
Sample Input
1
1 3 4 5
#include <iostream>
#include <malloc.h>
using namespace std;
 
typedef struct node{
    int data;
    struct node *next;
}LinkList;
 
int main(){
    int n;
    cin>>n;
    LinkList *l,*end,*body;
    l=(LinkList*)malloc(sizeof(LinkList));
    end=l;
    int num;
    for(int i=0;i<n;i++){
        cin>>num;
        body=(LinkList*)malloc(sizeof(LinkList));
        body->data=num;
        end->next=body;
        end=body;
    }
    end->next=NULL;
    int index;
    cin>>index;
    if(index>1&&index<n){
        LinkList *head1=l;
        for(int i=0;i<index-2;i++){
            head1=head1->next;
        }
        LinkList *head2=l;
        for(int i=0;i<index;i++){
            head2=head2->next;
        }
        head1->next=head2;
        LinkList *head3=l->next;
        while(head3->next!=NULL){
            cout<<head3->data<<' ';
            head3=head3->next;
        }
        cout<<head3->data<<' ';
    }else{
        cout<<"error!";
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值