• c链表实现遇到的错误


    想完成一个链表发现有错误,代码如下:

    //http://ac.jobdu.com/problem.php?pid=1511
    //֮ǰÓÃlistʵÏֵģ¬½ñÌìÊÔÒ»ÏÂÓÃstructʵÏÖһϰÉ
    //¿´¿´×Ô¼ºÄܲ»ÄÜʵÏÖÒ»¸öÁ´±í
     
    #include<iostream>
    using namespace std; 
    
    struct Node{
    	int num;
    	struct Node *next;
    };
    
    int main(void)
    {
    	struct Node n1;
    	
    	n1.num=1;
    
    	struct Node *head;
    	head=&n1;
    	n1.next=NULL;
    	struct Node *tail;
    	tail=head;
    	
    	int n;
    	cin>>n;
    	while(n)
    	{
    		struct Node node;
    		node.num=n;
    		node.next=NULL;
    		(*tail).next=&node;
    		*tail=node;
    		cin>>n;
    		
    	}
    	
    	struct Node *p;
    	p=head;
    	
    	while(p!=NULL)
    	{
    		cout<<(*p).num<<endl;
    		p=p->next;
    	}
    	
    }
    

      最后打印的时候只打印最后一个值,想了想应该是赋值的时候的错误,由于赋值是在while循环里,导致node是局部变量,用完之后就销毁了,而链表也并没有在初始化的时候给分配相应的空间。所以只存留了最后一个。

    解决办法:事先分配好空间。

    看了网上的实现,也都是预先分配好空间的,都使用了malloc,这样在空间在销毁之前都是存在的,所以你赋值之后,局部变量没了,但是值已经赋给相应的空间了。

    下边这样就是对的了:

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    
    struct Node {
    	int num;
    	struct Node *next;
    };
    
    int main(void)
    {
    	struct Node *head;
    	head = NULL;
    	struct Node *tail;
    	tail = head;
    
    	int n;
    	cin >> n;
    	while (n != -1)
    	{
    		struct Node *p=(struct Node *)malloc(sizeof(struct Node));
    		p->num = n;
    		p->next = NULL;
    
    		if (head == NULL)
    		{
    			head = p;
    			tail = p;
    			//head=&node; 
    		}
    		else
    		{
    			tail->next = p;
    			tail = tail->next;
    		}
    		//	cout<<(*tail).num<<endl;
    		cin >> n;
    	}
    
    	struct Node *p;
    	p = head;
    //	int i = 1;
    	while (p != NULL)
    	{
    		//cout << i++;
    		cout << (*p).num << " ";
    		p = p->next;
    	}
    
    
    
    }
    

      猜测:用的空间没有释放,如果经常这么做可能会导致内存问题

  • 相关阅读:
    IOS开发-cell的动态高度
    IOS开发-视频,音频,录音简单总结
    cocoapods的安装及注意事项
    CUICatalog: Invalid asset name supplied: (null) _configureCellForDisplay:forIndexPath
    IOS开发—数据库的使用
    IOS开发-键盘通知自定义键盘
    IOS开发-手势简单使用及手势不响应处理办法
    IOS开发-UITextField代理常用的方法总结
    Linux Shell 编程学习笔记
    Java的进程内缓存框架:EhCache
  • 原文地址:https://www.cnblogs.com/wswang/p/5144756.html
Copyright © 2020-2023  润新知