题解 | #遍历链表#

遍历链表

https://www.nowcoder.com/practice/7d348aa8b7d24e01a4f10bd023e2fb54

#include <iostream>
using namespace std;
int n;
struct node{
    int v;
    struct node* next;
};
typedef struct node* list;
int main() {
    while(cin >> n)
    {
        list head = (list)malloc(sizeof(list));
        head->v = 0;
        head->next = NULL;        
        list tail = head;
        for (int i = 1; i <= n; i++)
        {
            list tmp = (list)malloc(sizeof(list));
            cin >> tmp->v;
            if(tmp->v > tail->v)
            {
                tmp->next = NULL;
                tail->next = tmp;
                tail = tail->next;
            }
            else 
            {
                list l = head;
                while(l->next->v <= tmp->v)
                {
                    l = l->next;
                }
                tmp->next = l->next;
                l->next = tmp;
            }
        }
        while(head->next)
        {
            cout << head->next->v << " ";
            head = head->next;
        }
        cout << endl;
    }
}

全部评论

相关推荐

10-17 16:07
门头沟学院 Java
牛牛大你18号:在汇报,突然弹出来,,领导以为我在准备跳槽,刚从领导办公室谈心出来
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务