我正在学习链表,我正在解决一个问题,您必须在循环单链表的节点之间添加一个节点。我的代码的问题是它没有在正确的位置添加节点。我找不到我的代码中有什么问题。用于在节点之间添加的函数是
add_node_in_bet
。
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *next;
int data;
};
void addTOend(struct node **tail, int info)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = info;
if (*tail == NULL)
{
*tail = temp;
(*tail)->next = (*tail);
}
else
{
temp->next = (*tail)->next;
(*tail)->next = temp;
*tail = temp;
}
}
void add_node_in_bet(struct node **tail, int info, int pos)
{
struct node *new = (struct node *)malloc(sizeof(struct node *));
struct node *p = (*tail)->next;
new->data = info;
if (p == *tail)
{
new->next = (*tail)->next;
(*tail)->next = new;
(*tail) = new;
}
else if(p==(*tail)->next)
{
new->next = p;
(*tail)->next= new;
}
else{
while (pos > 2)
{
p = p->next;
pos--;
}
new->next= p->next;
p->next=new;
}
}
void print(struct node **tail)
{
struct node *p;
p = (*tail)->next;
do
{
printf("%d ", p->data);
p = p->next;
} while (p != (*tail)->next);
}
int main()
{
struct node *tail = NULL;
addTOend(&tail, 69);
addTOend(&tail, 65);
addTOend(&tail, 19);
addTOend(&tail, 67);
addTOend(&tail, 68);
addTOend(&tail, 61);
addTOend(&tail, 64);
add_node_in_bet(&tail, 0, 2);
print(&tail);
}
我的代码得到的输出。
0 69 65 19 67 68 61 64
几个问题:
malloc
论点是错误的。else if(p==(*tail)->next)
中的条件始终为真,因为您的代码显式将p
设置为该值。我会从尾部的
p
开始,然后从那里循环。一种特定情况是当您想要更新尾部引用时。这可能是当该位置对应于尾部位置 并且不是 1 时。当它为 1 时,您将希望将新节点作为头节点,而不更新尾部引用。
事情可能是这样的:
void add_node_in_bet(struct node **tail, int info, int pos) {
struct node *new = malloc(sizeof(*new));
struct node *p = *tail;
new->data = info;
for (int i = 1; i < pos; i++) {
p = p->next;
}
new->next = p->next;
p->next = new;
if (p == *tail && pos > 1) {
*tail = new;
}
}