1. 程式人生 > >C++連結串列:判斷一個連結串列是否為迴文結構

C++連結串列:判斷一個連結串列是否為迴文結構

#include <iostream>
#include <string>
#include <stack>
using namespace std;

struct node {
    int value;
    node *next;
};

node *add_node(node *head, int value) {
    node *new_node = new node();
    new_node -> value = value;
    new_node -> next = NULL;
    node *p_node =
new node(); p_node = head; if(head == NULL) head = new_node; else { while(p_node -> next != NULL) { p_node = p_node -> next; } p_node -> next = new_node; } return head; } bool Reverse_jadge(node *head) { stack <node *>
node_stack; node * p_node; p_node = head; int temp = 0; while(p_node != NULL) { node_stack.push(p_node); temp++; p_node = p_node -> next; } for (int i = 0; i <= temp / 2; i++) { if (node_stack.top() -> value == head -> value) { node_stack.
pop(); head = head -> next; } else return false; } return true; } int main() { node *head = NULL; string str, str_s; cout << "please input the data of list1!" << endl; getline(cin, str); while(str.find(' ', 0) != string :: npos) { head = add_node(head, atoi(str.substr(0, str.find(' ', 0)).c_str())); str.erase(0, str.find(' ', 0) + 1); } head = add_node(head, atoi(str.c_str())); cout << "the result of Reverse adge is: " << endl; bool flag = Reverse_jadge(head); if(flag) cout << '\t' << "Ture!" << endl; else cout << '\t' << "False!" << endl; system("pause"); return 0; }