pta重排連結串列(一個很清晰的實現,完全模擬連結串列的實現)

某朝發表於2024-09-17
#include <iostream>
#include <iomanip>
#include <unordered_map>
#include <string>

using namespace std;

const int N = 100010;
unordered_map<string, string> neStr;
unordered_map<string, int> eStr;
string headStr;
int n;

// 反轉連結串列函式(字串版本)
string reverse(string headStr) {
    string curStr = headStr, prevStr = "-1";
    while (curStr != "-1") {
        string tempStr = neStr[curStr];
        neStr[curStr] = prevStr;
        prevStr = curStr;
        curStr = tempStr;
    }
    return prevStr;
}

// 獲取連結串列的中間節點
string getMidNode(string headStr) {
    if (neStr[headStr] == "-1") return headStr;
    string fast = headStr;
    string slow = headStr;
    while (neStr[fast] != "-1" && neStr[neStr[fast]] != "-1") {
        fast = neStr[neStr[fast]];
        slow = neStr[slow];
    }
    return slow;
}
void print(string l)
{
    string cur = l;
    while (cur != "-1")
    {
        cout << eStr[cur] << ' ';
        cur = neStr[cur];
    }
}
// 合併兩個連結串列
void merge(string l1, string l2) {
   
    while (l1 != "-1" && l2 != "-1")
    {
        string n1 = neStr[l1], n2 = neStr[l2];
        neStr[l2] = l1;
        neStr[l1] = n2;
        l2 = n2;
        l1 = n1;
    }
}

int main() {
    cin >> headStr;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        string addrStr, nextStr;
        int data;
        cin >> addrStr >> data >> nextStr;
        eStr[addrStr] = data;
        neStr[addrStr] = nextStr;
    }

    // 處理連結串列
    string mid = getMidNode(headStr);
    string nextPart = reverse(neStr[mid]);
    neStr[mid] = "-1"; // 斷開連結串列的前半部分和後半部分


    /*cout << endl;
    print(headStr);
    cout << endl;
    print(nextPart);*/
    merge(headStr, nextPart);

    cout << endl;
    // 列印連結串列
    string cur = nextPart;
  
    while (cur != "-1") {
        cout << setw(5) << setfill('0') << cur << ' ' << eStr[cur] << ' ' << neStr[cur] << endl;
        cur = neStr[cur];
    }

    return 0;
}

相關文章