1
當我嘗試刪除列表的第2個節點時,我得到的第一個元素等於零,第2個節點沒有更改即時通訊使用代碼塊版本13.12 .......... .................................................. ..刪除功能中的不需要的結果
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* Insert(struct node* head , int x)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(head == NULL) {
temp->data = x;
temp->next = NULL;
head = temp;
return head; }
temp->data = x;
temp->next = NULL;
struct node* temp1;
temp1 = head;
while(temp1->next != NULL) {
temp1= temp1->next;
}
temp1->next = temp;
return head;
}
struct node* Delete (struct node* head, int a)
{
struct node* temp1 = head;
if (a == 1)
head = temp1->next;
free (temp1);
return head;
for(int i = 0; i < a-2; i++)
temp1 = temp1->next;
struct node* temp2;
temp2 = temp1->next;
temp1->next = temp2->next;
free (temp2);
return head;
}
void print(struct node* head)
{
while(head != NULL)
{
printf("the data is %d \n", head->data);
head = head->next;
}
}
int main()
{
struct node* root = NULL;
int a,c;
printf("How many numbers ? : \n");
scanf("%d",&a);
for(int i = 0; i<a; i++)
{
printf("Enter a number:\n");
scanf("%d",&c);
root = Insert(root, c);
}
Delete(root, 2);
print(root);
return 0;
}
1) - >'if(a == 1)head = temp1-> next; free(temp1); return head;}' – BLUEPIXY
雖然我沒有讀到任何細節,但您還沒有將'Delete'的返回值分配給任何內容,比如'root'。 'root = Delete(root,2);' –