zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【数据结构复习】链表的倒置(头插法倒置)

链表数据结构 复习 倒置
2023-09-14 09:03:44 时间
#include <bits/stdc++.h>
using namespace std;
typedef int ElemType;
struct LNode{
    ElemType data;
    LNode *next;
};
LNode *head,*tail;

void init(){
    head = (LNode*)malloc(sizeof(LNode));
    head->next = NULL;
    tail = head;
}

void input_data(){
    int x;
    cin >> x;
    while (x!=-1){
        LNode *temp = (LNode*)malloc(sizeof(LNode));
        temp->data = x;
        temp->next = NULL;
        tail->next = temp;
        tail = temp;
        cin >> x;
    }
}

//关键函数
void _reverse(){
    LNode *p = head->next;
    head->next = NULL;
    while (p){
        LNode *temp = p->next;//记录下当前遍历到的这个节点的下一个
        p->next = head->next;//这个几点的下一个节点接在头结点后面的那个节点
        head->next = p;//头结点的后一个节点指向该节点,从而完成插入过程
        p = temp;
    }
}

void print(){
    LNode *temp = head->next;
    while (temp){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

int main(){
    init();
    //freopen("D://rush.txt","r",stdin);
    input_data();
    _reverse();
    print();
    fclose(stdin);
    return 0;
}