YTU.3174: 链表基本操作---指定结点删除

来源:互联网 发布:floyd算法的流程图 编辑:程序博客网 时间:2024/06/06 20:25

3174: 链表基本操作---指定结点删除

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 23  Solved: 20
[Submit][Status][Web Board]

Description

根据具有10个元素的整型数组构建链表,删除其中的指定结点3和6,并输出链表中所有元素的值。请完善如下程序:只需提交需要填写部分的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE
{
    int data;           //数据域
    struct NODE *next;  //指针域,指向下一个结点
} Node;
int main()
{
    Node *head, *p1, *p2;     //head头指针,p一般结点指针
    int a[] = {1,2,3,4,5,6,7,8,9,10};
    int i;
    head = (Node *)malloc(sizeof(Node)); //开辟头结点
    p1 = (Node *)malloc(sizeof(Node));
    p1->data = a[0];
    head->next = p1;
    for( i = 1 ; i < 10 ; i++)  //对链表进行赋值,创建包含1-10的链表
    {
        p2 = (Node *)malloc(sizeof(Node));
        p1->next = p2;
        p2->data = a[i];
        p2->next = NULL;
        p1 = p2;
    }
    p1 = head->next;
    p2 = p1->next;
    printf("%d",p1->data);
    while( p2 != NULL )
    {
        if( p2->data == 3 || p2->data == 6)     //对于数据域是3或者是6的结点进行删除
        {
            p1->next = p2->next;
            free(p2);
            /*******在下面填写代码***********/

            /*******在上面填写代码***********/
        }
        printf(" %d",p2->data);
        p1 = p2;
        p2 = p2->next;
    }
    return 0;
}

Input

Output

不存在3和6的链表序列

Sample Output

1 2 4 5 7 8 9 10

AC代码:

#include <stdio.h>#include <stdlib.h>typedef struct NODE{    int data;           //数据域    struct NODE *next;  //指针域,指向下一个结点} Node;int main(){    Node *head, *p1, *p2;     //head头指针,p一般结点指针    int a[] = {1,2,3,4,5,6,7,8,9,10};    int i;    head = (Node *)malloc(sizeof(Node)); //开辟头结点    p1 = (Node *)malloc(sizeof(Node));    p1->data = a[0];    head->next = p1;    for( i = 1 ; i < 10 ; i++)  //对链表进行赋值,创建包含1-10的链表    {        p2 = (Node *)malloc(sizeof(Node));        p1->next = p2;        p2->data = a[i];        p2->next = NULL;        p1 = p2;    }    p1 = head->next;    p2 = p1->next;    printf("%d",p1->data);    while( p2 != NULL )    {        if( p2->data == 3 || p2->data == 6)     //对于数据域是3或者是6的结点进行删除        {            p1->next = p2->next;            free(p2);            /*******在下面填写代码***********/            p2=p1->next;            /*******在上面填写代码***********/        }        printf(" %d",p2->data);        p1 = p2;        p2 = p2->next;    }    return 0;}

水!!!

阅读全文
0 0