[英]Deleting Nodes in a Linked List
經過大量的努力,我已經設法將一個從我的鏈表中刪除某個節點的函數拼湊在一起。 但是,出於純粹的興趣,我想知道如何從列表中刪除第一個節點,即頭部。
我的程序要求刪除一封信,例如。 Hello存儲在列表中,用戶輸入H進行刪除,所以現在列表是ello目前我的代碼,程序崩潰,好像H被刪除,沒有頭,程序不知道去哪里尋找清單。
下面是我目前的實現,關於如何修改此代碼的任何線索或提示(我希望保持類似於我的方式)允許頭節點刪除將非常感謝!
編輯:回應下面
FullList DeleteNode(FullList temp, char c) {
FullList remember;
FullList ptr;
while (temp.head->c != c) {
remember.head = temp.head;
temp.head = temp.head->next;
}
ptr.head = temp.head->next;
free(temp.head);
remember.head->next = ptr.head;
return temp;
}
int main(void) {
FullList List;
char c, s;
List.head = NULL;
while ((c=getchar()) != '.') {
List = addToEnd(List, c);
}
scanf(" %c", &s);
List = DeleteNode(List, s);
while (List.head != NULL) {
printf("%c", List.head->c);
List.head = List.head->next;
}
return 0;
}
typedef struct List {
char c;
struct List *next;
}List;
typedef struct {
List *head;
List *tail;
}FullList;
List *insertList(char c, List *t1) {
List *t = (List*)calloc(1, sizeof(List));
t->c = c ;
t->next = t1;
return t;
}
FullList addToEnd(FullList c, char element) {
if (c.head == NULL) {
c.head = c.tail = insertList(element, NULL);
}else {
c.tail->next = insertList(element, NULL);
c.tail = c.tail->next;
}
return c;
}
void DeleteNode(FullList temp, char c) {
FullList remember;
FullList ptr;
while (temp.head->c != c) {
remember.head = temp.head;
temp.head = temp.head->next;
}
ptr.head = temp.head->next;
free(temp.head);
remember.head->next = ptr.head;
}
int main(void) {
FullList List;
char c, s;
List.head = NULL;
while ((c=getchar()) != '.') {
List = addToEnd(List, c);
}
scanf(" %c", &s);
DeleteNode(List, s);
while (List.head != NULL) {
printf("%c", List.head->c);
List.head = List.head->next;
}
return 0;
}
現在的方式,在DeleteNode
,當您更改參數時,它只更改局部變量,而不是函數外部的變量。
你要么必須將傳遞FullList
到DeleteNode
通過指針,以便完成它的修改將是可見的來電,或修改本地一個並返回,調用者必須將返回FullList
其名單。
無論哪種方式, DeleteNode
所做的DeleteNode
必須對調用者可見。
如果不更改現有代碼,則無法執行此操作。
您正在將FullList
結構傳遞給DeleteNode()
函數。 這意味着對該結構的任何更改都不會在main
- 該函數正在獲取它的副本 。
您需要更改DeleteNode()
以接受指針:
void DeleteNode(FullList *temp, char c)
然后在調用main()
你會這樣做:
DeleteNode(&List, s);
通過這樣做,您可以在函數中更改temp->head
的值,它將在main()
temp->head = temp->head->next;
編輯:您需要的邏輯是:
temp->head->c == c
temp->head
替換為temp->head->next
temp->head
指定給臨時指針*previous
。 在指針*current
temp->head->next
指定temp->head->next
。 循環遍歷列表,移動兩個指針。 當您在current->c
找到匹配項時,請在current->c
current->next
previous->next
和free()
分配current
節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.