zoukankan      html  css  js  c++  java
  • for循环与while循环

          今天在写线性表的链式存储过程中,遇到了一个比较奇葩的问题,就是同一段程序,用for循环可以顺利执行,然而用while循环就提醒我“结点空间申请失败!!!”,考虑了一上午都没有头绪。记录下这个问题,日后继续探究。

    下面是用for循环实现单链表的创建

    //尾插法创建带头结点的单链表
    ListNode *CreatListL(int n,DataType *x)
    {
        ListNode *head,*p1,*p2;
        int i ;
        head = (ListNode *)malloc(sizeof(ListNode));
        if(head == NULL){
            printf("结点空间申请失败!!!
    ");
            return NULL;
        }
        p1 = head;
        for(i = 0;i < n;i++){
            p2 =(ListNode *)malloc(sizeof(ListNode));
            if(p2 == NULL){
                printf("结点空间申请失败!!!
    ");
                return NULL;
            }
            p2->data = *(x + i);
            p1->next = p2;
            p1 = p2;
        }
        p1->next = NULL;
        return head;
    }

    下面是用while循环实现单链表的创建:

    //尾插法创建带头结点的单链表
     2 ListNode *CreatListL(int n,DataType *x)
     3 {
     4     ListNode *head,*p1,*p2;
     5     int i = 0;
     6     head = (ListNode *)malloc(sizeof(ListNode));
     7     if(head == NULL){
     8         printf("结点空间申请失败!!!
    ");
     9         return NULL;
    10     }
    11     p1 = head;
    12     while(i < n){
    13         p2 =(ListNode *)malloc(sizeof(ListNode));
    14         if(p2 == NULL){
    15             printf("结点空间申请失败!!!
    ");
    16             return NULL;
    17         }
    18         p2->data = *(x + i);
    19         p1->next = p2;
    20         p1 = p2;
    i++;
    21 } 22 p1->next = NULL; 23 return head; 24 }
  • 相关阅读:
    在SQL使用正则表达式
    What is callback?
    readResolve()的使用
    What is a serialVersionUID and why should I use it?
    How to terminate a thread in Java
    Eclipse导入源文件出现编码的问题
    What is livelock?
    [转]不要迷失在技术的海洋中
    [转]基于.Net的单点登录(SSO)解决方案
    IIS网站真正301重定向的方法(包括首页和内页)
  • 原文地址:https://www.cnblogs.com/fsy12604/p/9860584.html
Copyright © 2011-2022 走看看