2013-03-23 103 views
-1
NODE* insertNode (NODE* head, NODE* pre, DATA item) 
{ 
//Local Declaration 
NODE* curr; 

//Statement 
if (!(curr = (NODE*)malloc(sizeof(NODE))) 
    printf("\amemory overflow in insert\n"); 

curr->data = item; 
if (pre == NULL) 
{ 
    //inserting before first node or to empty list 
    curr->next = head; 
    head = curr; 
} 
else 
{ 
    //inserting in middle or at the end 
    curr->next = pre->next; 
    pre->next = curr; 
} 

return head; 
} 

這就是我如何根據正在閱讀的書籍在現有列表中插入節點。但是,它並不真正告訴我在這裏如何定義prepre指向前驅節點。)如何定義pre指針,使其指向前驅節點?如何在C中插入節點C

+4

這沒有足夠的上下文成爲一個完整的問題。 – 2013-03-23 20:11:36

+0

我想如果'curr'和'next'在鏈表中,那麼'pre'已經指向前一個節點。 – 2013-03-23 20:12:15

+0

你可以發佈你的鏈表的整個代碼? – Bharat 2013-03-23 20:12:53

回答

2

This link是,恕我直言,鏈接列表的主要介紹。

什麼書示出的是 「3步驟鏈接」 ...

假設{A,B,C}的結構/節點,使得一個 ==>b ==>ç ==>NULL

然後插入NEW一個你第一個鏈接後立即: ==>b(這是第一個,因爲如果您先重設a的指針,您將會遇到嚴重問題b

然後像...... 一個 ==> ...所以我們有一個 ==> ==>b ==>鏈接ç ==>NULL


要做到這一點,節點必須具有指針在其中......是這樣的:

struct node{ 
    int i; 
    struct node* next; // this is the value that will be changed 
}; 

正如您所看到的,只要節點包含指向另一個節點的指針,節點的精確定義就無關緊要。


curr指向當前節點......所以得到「以前」,你可以創建一個免費指針到另一個節點,我認爲NODE* pre是你的問題。

但是這是不必要的,因爲使用->運算符比有幾個指針要簡單得多。您也可以使用它來指向其他節點。

因此,對於我的{a,b,c}示例,假設a,bc都是唯一的struct node s,如前所示連接。

struct node* curr = a; // a pointer to the head of the list 
struct node NEW = malloc(sizeof(struct node)); // make a new node 

NEW->next = curr->next; // set NEW's next to point to b through `curr->next` 
/* note that defining previous isn't necessary, b/c it is defined @ curr->next */ 
curr->next = NEW;  // set curr (a) to point to NEW instead of b 

只記得在你需要在單鏈表中使用的節點之前設置curr

+0

感謝您的一個很好的鏈接 – 2013-03-23 20:24:37

+0

@ProgrammingNerd一旦你進入擺動的東西,檢查出問題。有一些好的!另外,我讓我的例子更徹底。 – d0rmLife 2013-03-23 21:01:36