【002】鏈表翻轉

題目描述

翻轉一個鏈表
例如:1 2 3 4
輸出:4 3 2 1

輸入輸出

輸入

  • 第一行是n; 表示鏈表長度
  • 第二行是n個整數,表示鏈表每一位所存儲的內容
    輸出

    • 針對每組輸出,輸出翻轉後的鏈表的內容

示例輸入

4
1 2 3 4

示例輸出

4 3 2 1

題目分析

鏈表翻轉是比較經典的面試題目,其中也有很多坑,要注意NULL和head節點的處理。
這道題有兩種解法,迭代和遞歸,代碼如下:

#include <iostream>
using namespace std;

class Node {
public:
    int num;
    Node *next;
    Node():next(NULL) {}
    Node(int num):num(num), next(NULL) {}

    void display() {
        Node *tmp = this;
        while (tmp) {
            printf("%d ", tmp->num);
            tmp = tmp->next;
        }
        printf("\n");
    }
};

class Reverse {
public:
    Node* Iteration(Node* &head) {
        Node *current = head;
        Node *pre = NULL;

        while (current != NULL) {
            Node *next = current->next;
            current->next = pre;
            pre = current;
            current = next; 
        }

        return pre;
    }

    Node *Recursion(Node* &head) {
        if (head == NULL || head->next == NULL) return head;

        Node *newHead = Recursion(head->next);
        head->next->next = head;
        head->next = NULL;

        return newHead;
    }
};

int main(int argc, char *argv[]) {
    Node *head = NULL;
    Node *current = NULL;
    int n;
    scanf("%d", &n);
    while(n--) {
        int num;
        scanf("%d", &num);
        Node *tmp = new Node(num);
        if (head == NULL) head = tmp;
        else current->next = tmp;
        current = tmp;      
    }
    Reverse re;
    //head = re.Iteration(head);
    head = re.Recursion(head);
    head->display();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章