扭转双向链接列表。我无法弄清楚为什么这个实现不起作用

时间:2013-04-17 03:26:51

标签: c doubly-linked-list

所以这实际上反转了我的列表,但由于某种原因,我的tail-> next被设置为0而不是NULL。 这导致我的打印功能陷入无限循环。

struct ListNode     {     int值;     struct ListNode * next;     struct ListNode * previous;     };

void reverseList(struct ListNode** head,struct ListNode** tail)
{
struct ListNode* current = *head;
struct ListNode* temp;
while(current != NULL)
{
    temp = current->previous;
    current->previous = current->next;
    current->next = temp;
    current = current->previous;
}
temp = *head;
*head = *tail;
*tail = temp;
}

void printList(struct ListNode* head)
{
while(head != NULL)
{
    printf("%d <--> ",head->value);
    head = head->next;
}
printf("\n");
}

int main()
{
int i = 0;
struct ListNode* head = malloc(sizeof(struct ListNode));
struct ListNode* tail = malloc(sizeof(struct ListNode));
head->value = 1;
head->previous = NULL;
head->next = NULL;
tail = head;
insertAtHead(&head,5);
insertAtTail(&tail,10);
while(i < 5)
{
    insertAtHead(&head,i);
    ++i;
}
printList(head);
reverseList(&head,&tail);
printList(head);
}

0 个答案:

没有答案