Hi, abandon
← 文章列表

c/c++:逆序建立链表

2017年6月2日 · c

数据结构实验之链表三:链表的逆置

#include <iostream>
#include <cstring>
using namespace std;
struct node
{
    int data;
    struct node *next;
};


int main ()
{
    std::ios::sync_with_stdio(false);

    struct node *head, *tail, *p, *tmpNode;
    head = new node;
    head->next = NULL;
    tail = head;

    int num;

    while(1)
    {
        p = new node;
        p->next = NULL;
        cin >> num ;
        if(num == -1)
        {
            break;
        }
        p->data = num;
        tail->next = p;
        tail = p;
    }

    p = head->next;
    head->next = NULL;

    while(p->next != NULL)
    {
        tmpNode = p->next;
        p->next = head->next;
        head->next = p;
        p = tmpNode;
    }
    p->next = head->next;
    head->next = p;

    p = head->next;
    while(p->next != NULL)
    {
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<p->data<<endl;;

    return 0;
}
想聊聊这篇文章?去 GooseForum 讨论 ← 返回文章列表