建立长度为n的单链表,删除第i个结点之前的结点。
第一行为自然数n,表示链式线性表的长度;
第二行为n个自然数表示链式线性表各元素值;
第三行为指定的删除参数i。
指定删除位置合法时候,输出删除元素后的链式线性表的所有元素,元素之间用一个空格隔开。
输入不合法,输出"error!".
-----------------------------------------
5
1 2 3 4 5
3
________________________
1 3 4 5
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
int length,tar;
struct node *head,*p,*q,*temp,*t;
while(cin>>length)
{
head=(struct node *)malloc(sizeof(struct node));
int i,j;
p=head;
for(i=0;i<length;i++)
{
q=(struct node *)malloc(sizeof(struct node));
cin>>q->data;
p->next=q;
p=q;
}
p->next=NULL;
cin>>tar;
temp=head;
if(tar<=1 || tar>length)
{
cout<<"error!";
break;
}
else
{
t=(struct node *)malloc(sizeof(struct node));
for(j=0;j<tar-1;j++)
{
t=temp;
temp=temp->next;
}
t->next=temp->next;
length--;
}
temp=head;
temp=temp->next;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
return 0;
}