2016-12-20 71 views
-1

我在交換單鏈表中的節點時遇到問題。我的代碼當前工作時沒有任何節點是列表的開始。交換單鏈表中的兩個節點

編輯:我瞭解的ADT,所以我不能改變什麼功能的輸入和輸出。

typedef struct textbuffer *TB; 

struct textbuffer { 
    char *data; 
    TB next; 
}; 

void swapTB(TB tb, int pos1, int pos2) { 
    if (tb == NULL || pos1 == pos2) return; 
    int totalLines = linesTB(tb) - 1; 
    if (pos1 < FIRST_LINE || pos1 > totalLines || pos2 < FIRST_LINE || pos2 > totalLines) { 
     printf("Error: line number out of range, %d-%d.\n", FIRST_LINE, totalLines); 
     abort(); 
    } else { 
     TB all = tb; 
     int i = 0; 
     TB prevX = NULL; 
     TB currX = tb; 
     while (i != pos1) { 
      prevX = currX; 
      currX = currX->next; 
      i++; 
     } 

     int j = 0; 
     TB prevY = NULL; 
     TB currY = tb; 
     while (j != pos2) { 
      prevY = currY; 
      currY = currY->next; 
      j++; 
     } 

     if (prevX != NULL) { 
      prevX->next = currY; 
     } else { 
      all = currY; //update head of list 
     } 

     if (prevY != NULL) { 
      prevY->next = currX; 
     } else { 
      all = currX; //update head of list 
     } 

     TB temp = currY->next; 
     currY->next = currX->next; 
     currX->next = temp; 
    } 
    //return all; 
} 

我知道我的交換節點的方式是正確的,因爲如果我改變函數返回一個TB(在這種情況下,所有),那麼它的工作原理。

我的問題是如何將我與一個void函數和不改變什麼功能需要在做呢?我想我需要一個頭指針?但是,我該如何使用它?

+1

這個代碼看起來非常地複雜。順便提一下[mcve]。 –

+0

「TB」是一個隱藏指針嗎?否則它的可見性/範圍僅限於'swapTB'函數。 – LPs

+1

將這些信息添加到您的帖子中。 – LPs

回答

0

做兩件事情: - 你的結構textbuffer的 傳遞地址的功能。

空隙swapTB(TB * TB,INT POS1,INT POS2)

在main()

: -

swapTB(TB,POS1,POS2);

而且還要檢查你的currx和咖喱NULL與否。

typedef struct node *TB; 
struct node 
{ 
    int data; 
    TB next; 
}; 

TB head=NULL; 

void swapNodes(TB head_ref, int x, int y) 
{ 
    if (x == y) return; 
    head = head_ref; 

    struct node *prevX = NULL, *currX = head_ref; 
    while (currX && currX->data != x) 
    { 
     prevX = currX; 
     currX = currX->next; 
    } 

    struct node *prevY = NULL, *currY = head_ref; 
    while (currY && currY->data != y) 
    { 
     prevY = currY; 
     currY = currY->next; 
    } 

    if (currX == NULL || currY == NULL) 
     return; 

    if (prevX != NULL) 
     prevX->next = currY; 
    else 
     head = currY; 

    if (prevY != NULL) 
     prevY->next = currX; 
    else 
     head = currX; 

    struct node *temp = currY->next; 
    currY->next = currX->next; 
    currX->next = temp; 

} 

int main() 
{ 
    TB start=NULL; 
    // Create linked list here 

    swapNodes(start, pos1, pos2); 

    print_linkedlist(head); // print the linked list after swap 

    return 0; 
} 
+0

'TB ** tb' - >'TB * tb' ...爲什麼最好避免隱藏指針typedef – LPs

+0

@LPs我正在傳遞指針的地址,因爲我知道我們需要雙指針來保存地址因爲我建議OP傳遞單個指針的地址。 –

+0

'typedef struct textbuffer * TB;'....... – LPs