NODE* insertNode (NODE* head, NODE* pre, DATA item)
{
//Local Declaration
NODE* curr;

//Statement
if (!(curr = (NODE*)malloc(sizeof(NODE)))
    printf("\amemory overflow in insert\n");

curr->data = item;
if (pre == NULL)
{
   //inserting before first node or to empty list
   curr->next = head;
   head = curr;
}
else
{
   //inserting in middle or at the end
   curr->next = pre->next;
   pre->next = curr;
}

return head;
}


这就是我根据正在阅读的书在现有列表中间插入节点的方法。但是,它并没有真正告诉我这里如何定义prepre指向前任节点。)如何定义pre指针,使其指向前任节点?

最佳答案

恕我直言,This link是链接列表的主要介绍。

这本书所说明的是“三步链接”。

假设{a,b,c}是结构/节点,使得a ==> b ==> c ==> NULL

然后在第一个链接后立即插入NEW:NEW ==> b(这是第一个,因为如果首先重置a的指针,将很难进入b!

然后将a链接到NEW,例如... a ==> NEW ...,所以我们有一个==> NEW ==> b ==> c ==> NULL



为此,节点中必须包含指针...类似于:

struct node{
  int i;
  struct node* next; // this is the value that will be changed
};


如您所见,节点的精确定义并不重要,只要它包含指向另一个节点的指针即可。



curr指向当前节点...所以要获得“上一个”,您可以创建指向另一个节点的互补指针,因为我假设NODE* pre在您的问题中。

但这确实是不必要的,因为仅使用->运算符比拥有多个指针要简单得多。您也可以使用它指向其他节点。

因此,对于我的{a,b,c}示例,假定abc都是唯一的struct node,如前所示进行连接。

struct node* curr = a;   // a pointer to the head of the list
struct node NEW = malloc(sizeof(struct node)); // make a new node

NEW->next = curr->next;  // set NEW's next to point to b through `curr->next`
/* note that defining previous isn't necessary, b/c it is defined @ curr->next */
curr->next = NEW;        // set curr (a) to point to NEW instead of b


只需记住在单个链接列表中需要使用的节点之前设置curr

关于c - 如何在C的中间插入节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15591536/

10-11 23:17
查看更多