[英]Reversing a Linked List in C
我應該顛倒鏈表的順序,我認為我有正確的想法,但由於某種原因,當我打印出列表時,我的代碼進入無限循環,我不知道為什么我認為它有與接近結尾的for循環有關,因為當我評論該部分並再次測試它時,不再有無限循環了。
這是列表的外觀示例:
42, 36, 14, 17, 48, 36
這就是我想要得到的:
36, 48, 17, 14, 36, 42
以下是我的代碼:
// List element: a list is a chain of these
typedef struct element
{
int val;
struct element* next;
} element_t;
// List header - keep track of the first and last list elements
typedef struct list
{
element_t* head;
element_t* tail;
} list_t;
void reverse (list_t* L)
{
//getting the len of the list
unsigned int len = 0;
element_t* temp = L->head;
while (temp != L->tail)
{
len++;
temp = temp->next;
}
len++; //extra +1 len for tail since while loop does not include
//now for reversing
unsigned int i = 0;
element_t* ELEtail = L->tail;
element_t* ELEhead = L->head;
for (i = 0; i < len-1; i++)
{
ELEtail->next = ELEhead;
ELEhead = ELEhead->next;
ELEtail = ELEtail->next;
}
}
你在for循環中編寫的代碼是錯誤的。
為了給你一個想法讓我們舉個例子。 最初你的清單是
42 -> 36 -> 14 -> 17 -> 48 -> 36
| |
ELEhead ELEtail
就在for循環之前:ELEtail指向36(最后一個元素),ELEhead指向42(第一個元素)。
現在,在for循環的第一次迭代之后:ELEtail指向42並且ELEhead指向36(初始列表的第二個元素)並且列表變為
42 -> 36 -> 14 -> 17 -> 48 -> 36 -> 42
| |
ELEhead ELEtail
上面示例中的第一個和最后一個42是相同的元素。 因此它會產生無限循環。
現在要反轉鏈接列表,只需要一個指針來反轉鏈接列表的頭部。 每當您在原始鏈接列表中遇到新元素時,只需在反向鏈接列表的頭部輸入它即可。 當您在新鏈接列表的頭部插入原始鏈接列表的最后一個元素時,您的鏈接列表將被反轉。 為此你甚至不需要知道原始列表的長度。 這將保存您計算鏈表長度的第一個循環。
試試這個,您不需要知道列表或循環的大小。
void reverse_list(list_t* l) {
element_t* new_tail = l->head;
element_t* new_head = reverse(l->head); //Assumes l isn't NULL!
l->head = new_head;
l->tail = new_tail;
}
element_t* reverse(element_t* head) {
if(list == NULL)
return NULL;
if (list->next == NULL)
return head;
element_t* body = reverse(head->next);
head->link->link = head; // reverse head
head->link = NULL;
return body;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.