c - 在链接列表的末尾插入节点而不是值

标签 c arrays linked-list

假设我有一些链接列表已经可用,我想将每个单独列表的第一个节点存储到另一个列表中,这样我就可以调用这个列表来显示原始列表。我认为我们必须使用两种不同的结构。我已经成功地保留了原始列表并使用单个列表的第一个节点的数组来显示它们,但我想创建一个单个列表的链表来实现相同的。它具有预期的输出,但正如我所说,我想使用链表而不是节点数组。

现在这就是我试图解决将链表数组替换为第一个节点的链表的问题的方法,每当我尝试调试代码时都会崩溃。请帮助我。

#include <stdio.h>
#include <stdlib.h>

struct node{
    int number;
    struct node*next;
};

typedef struct node Node;
Node* insertValue(Node * list, int value);
void display(Node*);

struct list_of_nodes {
    Node *list;
    struct list_of_nodes *next;
};

 typedef struct list_of_nodes ListNode;

 ListNode* insertNode(ListNode* head,Node* node);

int main()
{
ListNode *head=NULL;
Node *globalList = NULL, *lists[100];
int nbrOfLists, listNo, nbrOfVal, valNo, val,i=0,k;

CHECKER:
printf("\n\n Enter the number of lists (1 to 100):");
scanf("%d", &nbrOfLists);

if(nbrOfLists <= 0 || nbrOfLists > 100) //handling exceptional cases
    {
        printf("\n \n Number of Lists should be between 1 to 100");  // since array of node pointers contains 100 elements
        goto CHECKER;
    }


for(listNo = 0; listNo < nbrOfLists; listNo++)
{
    printf("\n\n Enter the number of inputs to the list %d: \n ",listNo+1);
    scanf("%d", &nbrOfVal);
    lists[listNo] = NULL;

    for(valNo = 0; valNo < nbrOfVal; valNo++)   // to enter values in each individual list
    {
        printf("Enter node value %d:", valNo+1);
        scanf("%d", &val);

        // Here we insert the value in both lists
        lists[listNo]= insertValue(lists[listNo], val);  // original list has to be retained so storing in array lists
        globalList = insertValue(globalList, val);   // inserting node in combined list. This prevents an extra loop and merges the list elements into one.
    }

    head=insertNode(head,lists[listNo]); // CRASHING HERE 

    printf("\n  The list %d is: ",listNo+1);
    display(lists[listNo]);  // display each list after input
}

printf("\n\n\n THE FINAL LIST IS: ");
display(globalList);  //display combined list

printf("\n\n THE LISTS WERE: ");

while(i<nbrOfLists){   //original lists displayed
    k=i+1;
    printf("\n\n The list %d is: ",k);
    display(lists[i]);
    i++;
}

printf("\n\n");
return 0;
}

ListNode* insertNode(ListNode* head, Node* node){
ListNode *newNode, *m;
newNode = malloc(sizeof(ListNode));
newNode->list=node;

if(newNode == NULL)
{
   newNode->next=NULL;  // inserting first node
   return newNode;
}

m = head;
while(m->next)  // checking for right position in ordered list for new node
{
  m = m->next;
}
newNode->next = m->next;  // inserting new node
m->next = newNode;
return head;

}
Node* insertValue(Node * list, int value)   // function to insert node in ordered manner into list
{
Node *newNode, *m;
newNode = malloc(sizeof(Node));
newNode->number=value;

if(list == NULL)
{
   newNode->next=NULL;  // inserting first node
   return newNode;
}

if(value < list->number)
{
   newNode->next = list;  // inserting in end
   return newNode;
}

m = list;
while(m->next)  // checking for right position in ordered list for new node
{
   if(value < m->next->number)
       break;
   m = m->next;
}
newNode->next = m->next;  // inserting new node
m->next = newNode;
return list;
}

void display(Node*nodex){ // display node values in list

printf("%d ->",nodex->number);
nodex=nodex->next;

   if(nodex)
        return display(nodex);
   else
        return 0;
  }

这是显示预期结果但带有节点数组的代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct node{
    int number;
    struct node*next;
};

typedef struct node Node;
Node* insertValue(Node *list, int value);
void display(Node*);

int main()
{

    Node *globalList = NULL, *lists[100];
    int nbrOfLists, listNo, nbrOfVal, valNo, val, i = 0, k;

CHECKER:
    printf("\n\n Enter the number of lists (1 to 100):");
    scanf("%d", &nbrOfLists);

    if(nbrOfLists <= 0 || nbrOfLists > 100) //handling exceptional cases
    {
        printf("\n \n Number of Lists should be between 1 to 100");  // since array of node pointers contains 100 elements
        goto CHECKER;
    }

    for(listNo = 0; listNo < nbrOfLists; listNo++)
    {
        printf("\n\n Enter the number of inputs to the list %d: \n ", listNo + 1);
        scanf("%d", &nbrOfVal);
        lists[listNo] = NULL;

        for(valNo = 0; valNo < nbrOfVal; valNo++)   // to enter values in each individual list
        {
            printf("Enter node value %d:", valNo + 1);
            scanf("%d", &val);

            // Here we insert the value in both lists
            lists[listNo] = insertValue(lists[listNo], val);  // original list has to be retained so storing in array lists
            globalList = insertValue(globalList, val);   // inserting node in combined list. This prevents an extra loop and merges the list elements into one.
        }

        printf("\n  The list %d is: ", listNo + 1);
        display(lists[listNo]);  // display each list after input
    }

    printf("\n\n\n THE FINAL LIST IS: ");
    display(globalList);  //display combined list

    printf("\n\n THE LISTS WERE: ");

    while(i < nbrOfLists){   //original lists displayed
        k = i + 1;
        printf("\n\n The list %d is: ", k);
        display(lists[i]);
        i++;
    }

    printf("\n\n");
    return 0;
}

Node* insertValue(Node *list, int value)   // function to insert node in    ordered manner into list
{
    Node *newNode, *m;
    newNode = malloc(sizeof(Node));
    newNode->number = value;

    if(list == NULL)
    {
        newNode->next = NULL;  // inserting first node
        return newNode;
    }

    if(value < list->number)
    {
        newNode->next = list;  // inserting in end
        return newNode;
    }

    m = list;
    while(m->next)  // checking for right position in ordered list for new node
    {
        if(value < m->next->number)
            break;
        m = m->next;
    }

    newNode->next = m->next;  // inserting new node
    m->next = newNode;
    return list;
}

void display(Node *nodex){ // display node values in list

    printf("%d ->", nodex->number);
    nodex = nodex->next;

    if(nodex)
        return display(nodex);
    else
        return 0;
}

如果您不明白这个问题,请告诉我。

最佳答案

经过大量讨论 chat ,我最终使用了与问题中的最后一个版本密切相关的代码:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int number;
    struct node *next;
};

typedef struct node Node;
Node *insertValue(Node *list, int value);
void display(Node *);

struct list_of_nodes
{
    Node *list;
    struct list_of_nodes *next;
};

typedef struct list_of_nodes ListNode;

ListNode *insertNode(ListNode *head, Node *node);

int main(void)
{
    ListNode *head = NULL;
    Node *globalList = NULL, *lists[100];
    int nbrOfLists, listNo, nbrOfVal, valNo, val, i = 0, k;

CHECKER:
    printf("\n\n Enter the number of lists (1 to 100):");
    scanf("%d", &nbrOfLists);

    if (nbrOfLists <= 0 || nbrOfLists > 100)
    {
        printf("\n \n Number of Lists should be between 1 to 100");
        goto CHECKER;
    }

    for (listNo = 0; listNo < nbrOfLists; listNo++)
    {
        printf("\n\n Enter the number of inputs to the list %d: \n ", listNo + 1);
        scanf("%d", &nbrOfVal);
        lists[listNo] = NULL;

        for (valNo = 0; valNo < nbrOfVal; valNo++)
        {
            printf("Enter node value %d:", valNo + 1);
            scanf("%d", &val);

            lists[listNo] = insertValue(lists[listNo], val);
            globalList = insertValue(globalList, val);
        }

        head = insertNode(head, lists[listNo]);

        printf("\n  The list %d is: ", listNo + 1);
        display(lists[listNo]);
    }

    printf("\n\n\n THE FINAL LIST IS: ");
    display(globalList);

    printf("\n\n THE LISTS WERE: ");

    while (i < nbrOfLists)
    {
        k = i + 1;
        printf("\n\n The list %d is: ", k);
        display(lists[i]);
        i++;
    }

    printf("\n\n");
    return 0;
}

ListNode *insertNode(ListNode *head, Node *node)
{
    ListNode *newNode, *m;
    newNode = malloc(sizeof(ListNode));
    newNode->list = node;
    newNode->next = NULL;

    if (newNode == NULL)
    {
        fprintf(stderr, "Out of memory in %s\n", __func__);
        exit(1);
    }

    if (head == NULL)
        return newNode;

    m = head;
    while (m->next)
    {
        m = m->next;
    }
    newNode->next = m->next;
    m->next = newNode;
    return head;
}

Node *insertValue(Node *list, int value)
{
    Node *newNode, *m;
    newNode = malloc(sizeof(Node));
    newNode->number = value;
    newNode->next = NULL;

    if (list == NULL)
        return newNode;

    if (value < list->number)
    {
        newNode->next = list;
        return newNode;
    }

    m = list;
    while (m->next)
    {
        if (value < m->next->number)
            break;
        m = m->next;
    }
    newNode->next = m->next;
    m->next = newNode;
    return list;
}

void display(Node *nodex)
{
    printf("%d ->", nodex->number);
    nodex = nodex->next;
    if (nodex)
        display(nodex);
}

使用示例数据文件(ll7.data):

3
6 26 22 83 96 89 69
10 87 33 5 36 85 34 0 25 57 99
5 49 44 27 75 82

我编译了上面的ll7.c:

$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror ll7.c -o ll7
$

并在 valgrind 下运行它它注意到代码像筛子一样泄漏(因为看不到免费的),但在其他方面给了它一个干净的健康证明。

$ valgrind --suppressions=suppressions ./ll7 < ll7.data
==7696== Memcheck, a memory error detector
==7696== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7696== Using Valgrind-3.11.0.SVN and LibVEX; rerun with -h for copyright info
==7696== Command: ./ll7
==7696== 
--7696-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option
--7696-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 2 times)
--7696-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 4 times)


 Enter the number of lists (1 to 100):

 Enter the number of inputs to the list 1: 
 Enter node value 1:Enter node value 2:Enter node value 3:Enter node value 4:Enter node value 5:Enter node value 6:
  The list 1 is: 22 ->26 ->69 ->83 ->89 ->96 ->

 Enter the number of inputs to the list 2: 
 Enter node value 1:Enter node value 2:Enter node value 3:Enter node value 4:Enter node value 5:Enter node value 6:Enter node value 7:Enter node value 8:Enter node value 9:Enter node value 10:
  The list 2 is: 0 ->5 ->25 ->33 ->34 ->36 ->57 ->85 ->87 ->99 ->

 Enter the number of inputs to the list 3: 
 Enter node value 1:Enter node value 2:Enter node value 3:Enter node value 4:Enter node value 5:
  The list 3 is: 27 ->44 ->49 ->75 ->82 ->


 THE FINAL LIST IS: 0 ->5 ->22 ->25 ->26 ->27 ->33 ->34 ->36 ->44 ->49 ->57 ->69 ->75 ->82 ->83 ->85 ->87 ->89 ->96 ->99 ->

 THE LISTS WERE: 

 The list 1 is: 22 ->26 ->69 ->83 ->89 ->96 ->

 The list 2 is: 0 ->5 ->25 ->33 ->34 ->36 ->57 ->85 ->87 ->99 ->

 The list 3 is: 27 ->44 ->49 ->75 ->82 ->

==7696== 
==7696== HEAP SUMMARY:
==7696==     in use at exit: 43,752 bytes in 471 blocks
==7696==   total heap usage: 551 allocs, 80 frees, 49,880 bytes allocated
==7696== 
==7696== LEAK SUMMARY:
==7696==    definitely lost: 32 bytes in 2 blocks
==7696==    indirectly lost: 688 bytes in 43 blocks
==7696==      possibly lost: 0 bytes in 0 blocks
==7696==    still reachable: 29,998 bytes in 310 blocks
==7696==         suppressed: 13,034 bytes in 116 blocks
==7696== Rerun with --leak-check=full to see details of leaked memory
==7696== 
==7696== For counts of detected and suppressed errors, rerun with: -v
==7696== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
$

当输入来自文件时,并不是真正需要提示输出,这也是看不到数字的原因。当您在终端上键入时,终端驱动程序会将您键入的内容回显到屏幕上。当数据来自文件时,您看不到读取的字符。

抑制文件列出并抑制了 Mac OS X 10.10.3 Yosemite 运行时系统的各种泄漏。这就是为什么也有这么多内存在使用的原因;运行时系统使用大量内存。

如果全部是我的代码,会有很多不同的做法。应该添加很多错误检查和可以/应该完成的重构(尤其是“提取函数”),但这些更改并不是为了保留与问题中发布的代码的一些相似之处。

关于c - 在链接列表的末尾插入节点而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719445/

相关文章:

javascript - Javascript:如何检查一个数组是否恰好包含另一个数组?

java - 实现自己的LinkedList

c - 模拟 'strings' UNIX 命令的 C 程序运行时崩溃

scala - 为什么递归惰性列表会破坏 Scala 中的堆栈?

c - 如果在单独的线程中关闭(2) 文件描述符,select(2) 会做什么?

c++ - 将二维数组转换为 vector

c - Linux:如何检查是否创建了新进程

c# - 在 C# 中的数组中搜索字符串的开头

c# - 安装完软件后如何安装USB驱动

c - 在 C 中将函数标记为内联是否会导致所有调用的函数都被隐式标记为内联?