c - 尝试使用两个指针在c中查找middel但程序崩溃链表
问题描述
我使用两个指针编写遍历链表的函数。一个指针移动一个,另一个指针移动两个。当快指针到达末端时,慢指针将到达链表的中间。但是当我尝试将临时指针移动两个时我的代码崩溃了
#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 检查条件之后,dur totemp=temp->next
行将temp
指向NULL
。在下temp=temp->next
一行中,您尝试取消引用该NULL
. 那会崩溃
2)列表有2个元素。while 条件检查temp
后将指向最后一个元素。并且在下temp=temp->next
一行之后temp
将指向NULL
。现在在下一行中,您尝试取消引用该NULL
. 这是另一个崩溃点
您需要temp=temp->next
从内部循环中删除一个,因为它在每次循环迭代中前进temp
3 个位置,这显然是一个逻辑错误。删除其中一个后不会消除崩溃机会的节点。
另一件事是注释代码也是错误的。
// new->next=med;
//med->next=new;
你可能想做-
new->next = med->next;
med->next = new;
推荐阅读
- php - Rest API:保存一个值以供合理数量的并发用户以后使用
- php - 在 PHP + PostgreSQL 的查询中使用变量和表名的正确方法是什么?
- cassandra - DataStax Bulk Loader - 更改 Cassandra 中的日期格式
- sql - 在 Postgres 中将列数据类型从 String 更改为 Float。错误
- macos - 我能否像开发 iOS 应用程序一样,使用构建服务器通过 Visual Studio for Windows 和 Xamarin 开发 MacOS 桌面应用程序?
- python - 使用网格后有没有办法移动标签
- ruby-on-rails - 尝试为条带 api 传递/获取数据
- javascript - React Native:从
进入在组件外部声明的函数 - c# - C# - Process.Start() 不会在 Windows Server 2019 上启动 ClickOnce 应用程序 - 在 2008 R2 上运行良好
- java - 在我的 Swing 应用程序中关闭弹出窗口时运行一些代码