首页 > 解决方案 > 尝试使用两个指针在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 未在链表中添加任何内容,因为当我尝试在链表中间找到时代码崩溃

标签: clinked-list

解决方案


崩溃是由于这两行 -

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从内部循环中删除一个,因为它在每次循环迭代中前进temp3 个位置,这显然是一个逻辑错误。删除其中一个后不会消除崩溃机会的节点。

另一件事是注释代码也是错误的。

//  new->next=med;
//med->next=new;

你可能想做-

new->next = med->next;
med->next = new;

推荐阅读