实验1:单向链表就地转置

  实验1:单向链表就地转置:

老师说随便语言,所以用的是c和c++混用方便一些。

一:实验要求:

1.新建单链表
2.依次输出单链表的值
3.就地反转
4.输出反转的链表的值
5.摧毁单链表

 

二:实验代码:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using std::cin;
using std::cout;
using std::endl;

struct Link
{
    Link* next;
    int number;
};

void InitLink(Link* h1) {//头结点没有值
    int n;
    int number;
    cout<<"请输入您要创建链表的元素个数"<<endl;
    cin >> n;
    cout<<"请输入您要创建的链表,并且每一个元素请用空格空出"<<endl;

    for (int i = 0; i < n; i++) {
        Link* h2 = (Link*)malloc(sizeof(Link));
        cin >> number;
        h2->number = number;
        h2->next = NULL;
        h1->next = h2;
        h1 = h1->next;
    }
}

void  ReverseLink(Link* h) {
    cout << "下面是转置后的结果:"<<endl;

    Link* h0 = h->next;

    Link* cu=NULL, * pr = NULL;
    while (h0 != NULL) {
        cu = h0;
        h0 = h0->next;
        cu->next = pr;
        pr = cu;
    }

    h->next = cu;
    cout << "下面是转置后的结果:"<<endl;
}

void showLink(Link* h) {
    while (h->next!=NULL) {
        cout << h->next->number<<" ";
        h = h->next;
    }
    cout<<endl;
}

void destoryLink(Link* h) {
    Link* str = h;
    while (str!=NULL) {
        Link* temp = str->next;
        free(str);
        str = temp;
    }
    h = NULL;
    cout << "您已清除"<<endl;
}

int main() {
    int ck;
    int n;
    Link* head = (Link*)malloc(sizeof(Link));
    head->next = NULL;

    InitLink(head);
    showLink(head);
    ReverseLink(head);
    showLink(head);
    destoryLink(head);
    return 0;
}

 

三:结果:

 

posted @ 2020-10-17 13:47  焕不涣  阅读(332)  评论(0编辑  收藏  举报