用C/C++码经典算法--链表

All rights reserved by DianeSoHungry (Qingyun Hu).
Original URL: https://www.cnblogs.com/DianeSoHungry/p/8276032.html

Content

  • Problem 1: Print a linked list backwards with stack
  • Problem 2: Reverse a linked list in place.

Problem 1

Print a linked list backwards with stack

Solution in CPP

//  Created by Qingyun Hu on 8/30/19.
//  Copyright © 2019 Qingyun Hu. All rights reserved.
//
// print a linked list backwards with stack.

#include<iostream>
#include<stack>
struct ListNode{
    int val;
    ListNode* next;
    ListNode(int val):val(val){
    }
};

ListNode* CreateLinkedList(){
    int n;
    std::cin >> n;
    ListNode* head = new ListNode(0);
    ListNode* cur = head;
    for (int i = 0; i < n; ++i){
        cur->next = new ListNode(0);
        std::cin >> cur->next->val;
        cur = cur->next;
    }
    return head->next;
}

int main(){
    ListNode* linked_list = CreateLinkedList();
    std::stack<ListNode*> stck;
    while(linked_list){
        stck.push(linked_list);
        linked_list = linked_list->next;
    }
    while(!stck.empty()){
        std::cout << (stck.top()->val) << " ";
        stck.pop();
    }
    
    return 0;
}

Test Case

input

4
23 1 6 2

output

2 6 1 23 Program ended with exit code: 0

Problem 2

Reverse an linked list in place.

Solution in CPP

//  Created by Qingyun Hu on 8/30/19.
//  Copyright © 2019 Qingyun Hu. All rights reserved.
//
// Reverse a linked list in place.
#include <iostream>
#include <stack>
struct ListNode{
    int val;
    ListNode* next;
    ListNode(int val):val(val){
        
    }
};

ListNode* CreateLinkedList(){
    int n;
    std::cin >> n;
    ListNode* head = new ListNode(0);
    ListNode* cur = head;
    for (int i = 0; i < n; ++i){
        cur->next = new ListNode(0);
        std::cin >> cur->next->val;
        cur = cur->next;
    }
    return head->next;
}

ListNode* ReverseLinkedList(ListNode* head){
    ListNode* reversed_list = nullptr;
    ListNode* cur = head;
    ListNode* org_list;
    while(cur){
        org_list = cur->next;
        cur->next = reversed_list;
        reversed_list =  cur;
        cur = org_list;
    }
    return reversed_list;
};

int main(){
    
    ListNode* linked_list = CreateLinkedList();
    ListNode* reversed_list = ReverseLinkedList(linked_list);
    while (reversed_list) {
        std::cout << reversed_list->val << " ";
        reversed_list = reversed_list->next;
    }
    return 0;
}

Test Case

input

4
1 4 2 66

output

66 2 4 1 Program ended with exit code: 0

Reference

《剑指offer》何海涛

原文地址:https://www.cnblogs.com/DianeSoHungry/p/8276032.html