且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从给定的 LinkedList 在 C++ 中创建一个反向 LinkedList

更新时间:2023-11-10 08:05:04

更简单的一个:遍历你的链表,保存上一个和下一个节点,让当前节点指向上一个:

Easier one: Go through your linked list, save the previous and the next node and just let the current node point at the previous one:

void LinkedList::reversedLinkedList()
{
    if(head == NULL) return;

    Node *prev = NULL, *current = NULL, *next = NULL;
    current = head;
    while(current != NULL){
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    // now let the head point at the last node (prev)
    head = prev;
}