[Simple algorithm] 23. Reverse linked list

topic:

Given a linked list, delete the nth node from the bottom of the linked list and return the head node of the linked list.

Example:

Given a linked list: 1 -> 2 -> 3 -> 4 -> 5 , and n = 2 .

When the penultimate node is removed, the linked list becomes 1 -> 2 -> 3 -> 5 .
illustrate:

The given n is guaranteed to be valid.

Advanced:

Can you try to implement it using one pass scan?

Have you encountered this question in a real interview session?

1. Solution:

Recursive implementation, very simple:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList1(ListNode* head) {
        struct ListNode* pNode;
        struct ListNode* reverseHead = NULL;

        if(head == NULL){
            return NULL;
        }

        while(head){
            pNode = head;
            head = head->next;
            if(reverseHead == NULL){
                reverseHead = pNode;
                reverseHead->next = NULL;
            }else{
                pNode->next = reverseHead;
                reverseHead = pNode;
            }
        }

        return reverseHead;
    }
    
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL){
            return head;
        }
        
        ListNode * newHead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        
        return newHead;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206631&siteId=291194637