經過很多努力,我已經設法將一個從我的鏈接列表中刪除某個節點的函數拼湊在一起。但是,出於純粹的興趣,我想了解如何從列表中刪除第一個節點,即頭部。刪除鏈接列表中的節點
我的程序要求刪除一個字母,例如。 你好存儲在列表中,用戶輸入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;
}
我按照您的建議修改了代碼,但是現在,它會刪除所有內容,直到輸入的字母爲止。即Abcde,輸入c,de打印 – PnP
如果可能,請參閱我的編輯,我已返回FullList而不是使用指針,但得到相同的結果,它會刪除所有內容,直到我輸入的字母爲止。 – PnP
@ user1048116 - 我現在解釋了改變'temp-> head'的值,我沒有爲你做功課;)你需要構建從頭部開始尋找匹配的邏輯。作爲一個提示,你將需要兩個指針 - 「* previous」和「* current」。您需要從頭開始,跟蹤前一個和當前節點,並在'current-> c'中查找您的匹配項。當你找到你想要刪除的節點時,你必須將'current-> next'分配給'previous-> next',然後''free''當前'節點。沒有必要從這個函數中返回任何東西 - 你正在通過指針修改結構體 –