题解 | #遍历链表#

遍历链表

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;
    }
}

全部评论

相关推荐

华泰证券信息技术部 软开 月base2.2w,年终要看当年收益,HR讲往年应届平均35W
点赞 评论 收藏
分享
kl_我是东山啊:《相关公司:阿里巴巴》
投递阿里巴巴等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务