c - C 中的链接列表插入放置功能出现问题。

标签 c linked-list

事情就是这样。我可能在这方面超出了我的能力范围(对于 C 和一般编程来说相当陌生)。我收到段错误,并且 fn 并没有真正执行我需要的操作(如注释所示)。我真的很感激这里的任何见解。我要去读一堆书,或多或少是按照步骤到达这一点的,所以我为此道歉,但我想我在阅读时会在那里排队。

The idea is if input was:
1
2
3
4

Output should be:
1
1 2
1 2 3
1 2 3 4

提前致谢!

#include "orderedList.h"

Node *orderedInsert (Node * p, int newval)
/* Allocates a new Node with data value newval
   and inserts into the ordered list with 
   first node pointer p in such a way that the
   data values in the modified list are in 
   nondecreasing order as the list is traversed.
*/
{
if(p == NULL)
   {
      p = malloc(sizeof(Node));
      p->data = newval;
      p->next = NULL;
      return p;
   }


Node * tmp = malloc(sizeof(Node));

  tmp->data = newval;

   while(p != NULL && p->data < tmp->data)
   {

    p = p->next;
   }

   p->data = tmp->data;
   p->next = NULL;
   return p;
}

void printList (Node * p)
/* Prints the data values in the list with 
   first node pointer p from first to last,
   with a space between successive values.
   Prints a newline at the end of the list.
*/
{
  while (p != NULL)
    {
      printf("%d \n", p->data);
      p = p->next;
    }
}

最佳答案

这有点棘手。您可以使用Node**(指向节点指针的指针)来跟踪正确的插入位置。

这段代码应该可以工作:

Node *orderedInsert (Node * p, int newval)
/* Allocates a new Node with data value newval
   and inserts into the ordered list with 
   first node pointer p in such a way that the
   data values in the modified list are in 
   nondecreasing order as the list is traversed.
*/
{
   Node * tmp = malloc(sizeof(Node));   // will need a new node anyway, so put it first
   if(tmp == NULL)
       return 0;                        // no memory error

   tmp->data = newval;

   if(p == NULL || newval < p->data)    // this will also handle the case
   {                                    //   when the new node is the first
      tmp->next = p;
      return tmp;
   }

   Node** pp = &p->next;                // the pointer to pointer
                                        //   where the new node is inserted
   while((*pp) != NULL && (*pp)->data < tmp->data)
   {
     pp = &(*pp)->next;
   }
   tmp->next = *pp;      // *pp is the rest of the list that comes after new node
   *pp = tmp;            // now insert the new node
   return p;             // return the beginning of the list
}

关于c - C 中的链接列表插入放置功能出现问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22724146/

相关文章:

c - 指针链表 C

java - Java 链表

c - PB7 上的 Atmega2560 PWM

c - 如何将相同的值写入 x86 中的连续位置

c++ - 我的双向链表项目出现 c2955 错误

c - 用于创建具有插入、删除和搜索功能的查找表的源代码片段

c - 32 位系统中积分算法更快

python - 在垃圾收集中调试 python 段错误

c - 交换指针而不是 memcpy

c++ - 递归返回链表中的最后一个节点