如標題所述,我必須洗掉鏈表中的相鄰重復項,這樣如果輸入是“google”,則輸出應該是“le”。我應該用 C 撰寫代碼。我已經撰寫了 70% 的代碼,除了我不知道如何連續回圈直到所有相鄰的重復項都被洗掉。我在 remove_adjacent_duplicates() 函式中洗掉相鄰的重復項,并且由于我不知道如何將終止條件放入回圈中,所以我只使用了 if-else 回圈。但是我在 remove_adjacent_duplicates() 函式中的代碼可能包含錯誤,所以如果有請糾正它,并請給出回圈解決方案,直到所有相鄰的重復項都被洗掉。這是我的代碼-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node //node creation
{
char data;
struct node *next;
};
void remove_adjacent_duplicates(struct node** head_ref)
{
struct node* current = *head_ref;
struct node* cnext = NULL; //the one next to current one
int flag=0;
cnext = current->next; //storing next
//printf("%c %c %d\n",current->data,cnext->data,flag);
if(cnext->data==current->data)
{
flag=1;
while(cnext->data==current->data)
{
cnext=cnext->next;
}
current=cnext;
cnext = current->next; //storing next
}
else
{
current=current->next;
cnext = current->next; //storing next
}
//printf("%c %c %d\n",current->data,cnext->data,flag);
if(flag) *head_ref = current;
}
void push(struct node** head_ref, char new_data)
{
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printList(struct node* head)
{
if (head == NULL)
{
printf("NULL\n\n");
return;
}
printf("%c->",head->data);
printList(head->next);
}
int main()
{
char s[100];
int i;
struct node* a = NULL;
printf("Enter string: ");
scanf("%s",s);
for(i=strlen(s)-1;i>-1;i--){
push(&a, s[i]); //last in first out, so in reverse g is last but first to come out
}
printf("\nConverting string to linked list: \n");
printList(a);
//printf("%c",current->data); prints first letter of a
remove_adjacent_duplicates(&a);
printList(a);
return 0;
}
uj5u.com熱心網友回復:
你可以使用遞回。這樣,您可以檢查遞回呼叫之前或遞回呼叫之后是否有要洗掉的內容:
void remove_adjacent_duplicates(struct node** head_ref)
{
struct node* current = *head_ref;
if (current == NULL || current->next == NULL) return;
int isEqual = current->data == current->next->data;
remove_adjacent_duplicates(¤t->next);
if (current->next != NULL && current->data == current->next->data) {
// Duplicates! Remove pair
*head_ref = current->next->next;
free(current->next);
free(current);
} else if (isEqual) {
// Continue ongoing removal
*head_ref = current->next;
free(current);
}
}
uj5u.com熱心網友回復:
幾個問題...
- 串列的第一個元素(例如頭部)永遠不能重復
- 洗掉 dup 時代碼會泄漏記憶體,因為它不這樣做
free - 該代碼僅洗掉第一個元素。
- 代碼使用了next,cur,但沒有使用previous,所以演算法需要重構。
- 鑄造回報
malloc是不好的。請參閱:我是否強制轉換 malloc 的結果? scanf是有問題的。%s可以超出陣列的末尾。更好地使用(例如)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530135.html標籤:C指针数据结构链表
