师--链表的结点插入

    xiaoxiao2021-03-25  141

    think: 1链表的查询操作+ 链表的顺序插入操作+链表的输出操作

    sdut原题链接

    师–链表的结点插入 Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description 给出一个只有头指针的链表和 n 次操作,每次操作为在链表的第 m 个元素后面插入一个新元素x。若m 大于链表的元素总数则将x放在链表的最后。

    Input 多组输入。每组数据首先输入一个整数n(n∈[1,100]),代表有n次操作。 接下来的n行,每行有两个整数Mi(Mi∈[0,10000]),Xi。

    Output 对于每组数据。从前到后输出链表的所有元素,两个元素之间用空格隔开。

    Example Input 4 1 1 1 2 0 3 100 4

    Example Output 3 1 2 4

    Hint

    Author

    以下为accepted代码

    #include <stdio.h> #include <stdlib.h> struct node { int Data; struct node *next; }*head; void Insert(int m, int x);//链表元素插入 void Pri(struct node *h);//链表元素输出 int main() { int n, m, x; while(scanf("%d", &n) != EOF) { head = (struct node *)malloc(sizeof(struct node)); head->next = NULL; while(n--) { scanf("%d %d", &m, &x); Insert(m, x);//插入操作 } Pri(head);//输出操作 } return 0; } void Pri(struct node *h)//链表元素输出函数 { struct node *p; p = h->next; while(p != NULL) { printf("%d%c", p->Data, p ->next == NULL? '\n': ' '); p = p->next; } } void Insert(int m, int x)//链表元素插入函数 { int cnt = 0; int flag = 0;//判断元素是否插入(判断插入元素位置) struct node *p, *q; q = (struct node *)malloc(sizeof(struct node)); q->Data = x; p = head; while(p->next != NULL) { if(cnt == m) { flag = 1; q->next = p->next; p->next = q; } cnt++;//寻找插入位置 p = p->next;//寻找插入位置 } if(flag == 0)//(链表只有头结点)||(m大于等于链表的元素总数) { q->next = p->next; p->next = q; } } /*************************************************** User name: Result: Accepted Take time: 0ms Take Memory: 136KB Submit time: 2017-03-09 14:58:57 ****************************************************/
    转载请注明原文地址: https://ju.6miu.com/read-12200.html

    最新回复(0)