[英]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.