西南科技大学OJ题 单链表的删除操作的实现0953

单链表的删除操作的实现

 1000(ms)

 65535(kb)

 2896 / 13622

建立长度为n的单链表,删除第i个结点之前的结点。

输入

第一行为自然数n,表示链式线性表的长度;
第二行为n个自然数表示链式线性表各元素值;
第三行为指定的删除参数i。

输出

指定删除位置合法时候,输出删除元素后的链式线性表的所有元素,元素之间用一个空格隔开。
输入不合法,输出"error!"。

样例输入

5
1 2 3 4 5
3

样例输出

1 3 4 5

#include<stdio.h>
#include<malloc.h>
struct LinkNode
{
    int data;
    struct LinkNode* next;
};

struct LinkNode* CreateList(int n)
{
    struct LinkNode *head,*p1,*p2;
    head=p1=p2=(struct LinkNode*)malloc(sizeof(struct LinkNode));
    scanf("%d",&p1->data);
    for(int i=1;i<n;i++)
    {
        p2=(struct LinkNode*)malloc(sizeof(struct LinkNode));
        p1->next=p2;
        p1=p2;
        scanf("%d",&p1->data);
    }
    p1->next=NULL;
    return head;
}
bool ListDelete(struct LinkNode*&head,int i,int n)
{
    struct LinkNode *p,*q;
    p=head;
    if(i<=1||i>n+1)
    return false;
    if(i==2)
    {
        head=p->next;
        free(p);
    }
    else
    {
        for(int j=0;j<i-3;j++)
        {
            p=p->next;
        }
        q=p->next;
        p->next=q->next;
        free(q);
    }
    return true;
}
int main()
{
    int n,i;
    struct LinkNode *head,*p;
    scanf("%d",&n);
    head=CreateList(n);
    scanf("%d",&i);
    if(ListDelete(head,i,n))
    {
        p=head;
        while(p!=NULL)
        {
            printf("%d ",p->data);
            p=p->next;
        }
    }
    else
    {
        printf("error!");
    }

/* 
#include<stdio.h>
int main()
{
    int n,a[100],i;
    scanf("%d",&n);
    for(int j=0;j<n;j++)
    {
        scanf("%d",&a[j]);
    }
    scanf("%d",&i);
    if(i<=1||i>n+1)
    printf("error!");
    else
    {
        for(int j=0;j<n;j++)
        {
            if(j=i-2)
            for( ;j<n-1;j++)
            {
                a[j]=a[j+1];
            }
        }
        for(int j=0;j<n-1;j++)
        {
            printf("%d ",a[j]);
        }
    }
    
}
*/ 

猜你喜欢

转载自blog.csdn.net/qq_40593308/article/details/82559707
今日推荐