首页 > 试题广场 >

遍历链表

[编程题]遍历链表
  • 热度指数:13608 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
建立一个升序链表并遍历输出。

输入描述:
输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。


输出描述:
可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。
示例1

输入

4
3 5 7 9

输出

3 5 7 9
#include <stdio.h>
#include <stdlib.h>
typedef struct linknode{
    struct linknode * next;
    int value;
}linknode,*linklist;
int main() {
    int n=0;
    scanf("%d",&n);
    int a[n];
    linklist l=(linklist)malloc(sizeof(linknode));
    linknode *t=l;
    linknode* t1=l;
    t->value=-1;
    for(int i=0;i<n;i++){
        int temp;
        scanf("%d ",&temp);
        linknode *ln=(linklist)malloc(sizeof(linknode));
        ln->value=temp;
        while(t->value<temp&&t!=NULL){
            t1=t;
            t=t->next;
        }
        if(t==NULL){
            t1->next=ln;
            ln->next=NULL;
            t=l;t1=l;
        }else {
            t1->next=ln;
            ln->next=t;
            t=l;t1=l;
        }
    }
    t=t->next;
    while(t!=NULL){
        printf("%d ",t->value);
        t=t->next;
    }
    return 0;
}

编辑于 2024-03-02 23:08:59 回复(0)
#include <stdio.h>
#include <stdlib.h>

///KY216 遍历链表
typedef struct Node {
    int d;
    struct Node* next;
} Node, *Linklist;
int Insert(Linklist head, int x) {
    Node* p, *q;
    p = head;
    q = p->next;
    if (q && (q->d >= x)) {///如果第一个元素存在且比第一个元素小,则插在第一位
        Node* t = malloc(sizeof(Node));
        t->d = x;
        p->next = t;
        t->next = q;
        //printf("Insert %d between %d and %d\n",x,p->d,q->d);
        return 1;
    }
    while (p->next) {///插到两个数中间
        if ((p->d <= x) && (q->d >= x)) {
            Node* t = malloc(sizeof(Node));
            t->d = x;
            p->next = t;
            t->next = q;
            //printf("Insert %d between %d and %d\n",x,p->d,q->d);
            return 1;
        }
        p = p->next;
        q = p->next;
    }
    Node* t = malloc(sizeof(Node));///插到末尾
    t->d = x;
    t->next = NULL;
    p->next = t;
    return 1;
}
int main() {
    int n, i, x;
    Linklist head = malloc(sizeof(Node));
    head->next = NULL;
    //printf("%d",head->next);
    while (scanf("%d",  &n) != EOF) { // 注意 while 处理多个 case
        // 64 位输出请用 printf("%lld") to
        for (i = 0; i < n; i++) {
            scanf("%d", &x);
            Insert(head, x);
        }
        while (head->next) {
            //printf("address:%d d:%d\n",head->next,head->next->d);
            printf("%d ", head->next->d);
            head = head->next;
        }
    }
    return 0;
}

发表于 2023-01-28 20:59:40 回复(0)

问题信息

难度:
2条回答 12025浏览

热门推荐

通过挑战的用户

查看代码