题解 | #牛牛的单向链表#

牛牛的单向链表

https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4

#include <iostream>
using namespace std;

struct list{
    int data ;
    struct list * next;
};

int main() {
    int n;
    cin >> n;
    int ary[n];
    //保存数组值
    for(int i =0; i< n; ++i)
    {
        cin >> ary[i];
    }
    //创建头节点
    struct list * head;
    head = (struct list*)malloc(sizeof(list));
    if( NULL == head )
    {
        cout <<"error";
        exit(-1);
    }
    head->data = ary[0];
    head->next = NULL;

    //尾插法(头节点有值了,C++默认为0)
    for(int i =1; i< n; ++i)
    {
        list* new_node  = (list*)malloc(sizeof(list));
        list* last = head;
        new_node->data = ary[i];
        new_node->next = NULL;

        if(NULL == head) //链表为空
	    {
		    head = new_node; //以此节点为头节点
	    }
        while(NULL != (last ->next))
        {
            last = last->next;
        }
        //将新节点设置为尾节点
        last ->next = new_node;
    }
    //顺序输出链表每个节点的值,头节点有值,不是纯节点
    if(NULL == head)
	{
		printf("该链表为空\n");
		return -1;
	}
	while(NULL != head)
	{
		cout<< head->data <<" ";

		head = head->next;
	}

return 0;
    
    
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

01-26 19:51
门头沟学院 Java
isabener:怎么感觉像群发的呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务