2016-01-23 39 views
0

函數必須返回鏈表的地址,如果刪除了它的請求值,否則返回NULL,函數 search(int input,CellPtr list)非常好。 ..程序的 的實際工作輸出是正確的,直到它到達第二個函數實際上它並沒有打印任何刪除鏈接結構的值

#include<stdio.h> 
#include<stdlib.h> 
typedef struct cell *CellPtr; 
typedef struct cell { 
    int contents; 
    CellPtr next; 
} Cell; 
int search(int input, CellPtr list); 
CellPtr delete_cell(int input, CellPtr list); 
int main() 
{ 
    CellPtr list; 
    list = malloc(sizeof(Cell)); 
    list->contents = -2;        /*ONLY FOR TESTING*/ 
    list->next = malloc(sizeof(Cell)); 
    list->next->contents = 4; 
    list->next->next = malloc(sizeof(Cell)); 
    list->next->next->contents = -6; 
    list->next->next->next = malloc(sizeof(Cell)); 
    list->next->next->next->contents = 100; 
    printf("search(100, list) = %d\n", search(-6, list)); 
    if (list = delete_cell(-5, list) == NULL) 
     printf("not found"); 
    return 0; 
} 

CellPtr delete_cell(int input, CellPtr list) 
{ 
    int i, j; 
    CellPtr p, q, tmp; 
    if (i = search(input, list) == 0) { 
     return NULL; 
    } 
    p = list; 
    if (i == 1) { 
     list = p->next; 
     free(p); 
     return list; 
    } 
    for (j=1; j<i-1; j++) { 
     p = p->next;       /*to get the address of the cell pointing to wanted cell*/ 
    } 
    if (p->next->next == NULL) {    /*wanted cell is the last one in the list*/ 
     free(p->next); 
     p->next = NULL; 
     return list; 
    } 
    q = p->next; 
    while (q->next->next != NULL) {   /*q is the address of the cell one before the last cell*/ 
     q = q->next; 
    } 
    if ((input * list->contents > 0) && (input * q->next->contents < 0)) { 
     tmp = list; 
     list = tmp->next; 
     tmp->next = p->next->next; 
     free(p->next); 
     p->next = tmp; 
     return list; 
    } 
    if ((input * list->contents <0) && (input * q->next->contents > 0)) { 
     q->next->next = p->next->next; 
     free(p->next); 
     p->next = q->next; 
     q->next = NULL; 
     return list; 
    } 
    if ((input * list->contents >0) && (input * q->next->contents > 0)) { 
     q->next->next = p->next->next; 
     free(p->next); 
     p->next = q->next; 
     q->next = NULL; 
     return list; 
    } 
    if ((input * list->contents <0) && (input * q->next->contents < 0)) { 
     return NULL; 
    } 
} 
+0

的代碼是相當(list = delete_cell(-5,list)== NULL),它是否是'輸入'並刪除單元節點? – Pooya

+0

一個可能的問題是,'list = delete_cell ,list)== NULL'或者'list =(delete_cell(-5,list)== NULL)'?沒有圓括號,這意味着後面的一個 – Eric

回答

1

在這裏,當你初始化的最後一個元素:

list->next->next->next = malloc(sizeof(Cell)); 

你錯過初始化其next - 指向NULL。你必須添加:

list->next->next->next->next = NULL; 

否則,函數尋找一個不存在的元素(如delete_cell(-5, list)將取消引用未初始化的指針和PROGRAMM可能會崩潰(未定義行爲)

+0

謝謝修復它... – stringson