[英]try to find middel but program crash linked list in c with two pointers
我写 function 使用两个指针遍历链表。 一个指针移动一个,另一个指针移动两个。 当快指针到达末端时,慢指针将到达链表的中间。 但是当我尝试将临时指针移动两个时我的代码崩溃了
#include <stdio.h>
#include <stdlib.h>
#define MEM (struct node*) malloc(sizeof(struct node))
void addl(); //add elements at last
void print(); //print linked list
void addf(); //add element at first
void addm(); //add element at middel
struct node {
int data;
struct node* next;
};
struct node* head;
void addl()
{
struct node* new, *temp;
temp = head;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = 0;
if (temp == 0)
head = new;
else {
while ((temp->next != 0))
temp = temp->next;
temp->next = new;
}
}
void print()
{
struct node* temp = head; //
printf(" \n Elements are : ");
while (temp != 0) {
printf(" %d ", temp->data);
temp = temp->next;
}
}
void addf()
{
struct node* new;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = head;
head = new;
}
void addm()
{
struct node* new, *temp, *med;
temp = head;
med = head;
new = MEM; //MEM #define for dynamic memory allocation
printf("\n\t\tenter m any number : ");
scanf("%d", &new->data);
if (temp == 0)
head = new;
else {
while ((temp = temp->next != 0)) {
med = med->next;
temp = temp->next; //fist move
temp = temp->next; //2nd move when i add program crash
}
// new->next=med;
//med->next=new;
printf("\n\t\tDATA : %d\n", med->data);
}
}
int main()
{
head = 0;
int i = 5; //create linked list
while (i) {
system("cls");
addf();
addl();
i--;
}
addm();
print();
return 0;
}
截至目前,addm 未在链表中添加任何内容,因为当我尝试在链表中间找到时代码崩溃
崩溃是由于这两行 -
temp=temp->next;//for one move
temp=temp->next;//for second move when i add this program crash
让我们考虑两种情况——
1)列表只有一个元素。 然后在 while 检查条件之后,在temp=temp->next
line temp
将指向NULL
。 在下一个temp=temp->next
行中,您尝试取消引用NULL
。 那会崩溃
2)列表有2个元素。 while 条件检查后temp
将指向最后一个元素。 在 next temp=temp->next
line temp
之后将指向NULL
。 现在在下一行中,您尝试取消引用NULL
。 这是另一个崩溃点
您需要从内部循环中删除一个temp=temp->next
,因为它在每个循环迭代中将temp
提高 3 position,这显然是一个逻辑错误。 删除其中一个后不会消除崩溃机会的节点。
另一件事是注释代码也是错误的。
// new->next=med;
//med->next=new;
你可能想做-
new->next = med->next;
med->next = new;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.