反转链表

来源:互联网 发布:js文件加载失败 编辑:程序博客网 时间:2024/06/04 19:48
#include<iostream>using namespace std;typedef struct TNode{    int data;    struct TNode* next;}TNode;TNode* createL(int n) //创建链表{    TNode* head = NULL;    TNode* tial = NULL;    for (int i = 0; i < n; i++)    {        TNode* node = new TNode;        node->next = NULL;        cout << "请输入";        cin >> node->data;        if (head == NULL)        {            head = node;            tial = head;        }        else        {            tial->next = node;            tial = node;        }    }    tial->next = NULL;    return head;}void travel(TNode* head){    cout << "输出结果:" << endl;    TNode* p = head;    while (p != NULL)    {        cout << p->data << endl;        p = p->next;    }}TNode* reserve(TNode* head)  //反转链表,返回翻转后的头结点{    if (!head)        return head;    TNode* pre = head;    TNode* cur = head->next;    TNode* s;    while (cur != NULL)    {        s = cur->next;        cur->next = pre;        pre = cur;        cur = s;    }    head->next = NULL;    return pre;}int main(){    TNode* head = NULL;    head = createL(7);    travel(head);    head = reserve(head);    travel(head);    return 0;}