【數據結構復習】輸入一個鏈表,然后輸出它


輸入數字,-1結束就好
要記住在新申請節點的時候,這樣寫
LNode *temp = (Lnode*)malloc(sizeof(LNode));
即指向LNode的一個指針。
因為malloc返回的就是一個指針。

#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 print(){
    LNode *temp = head->next;
    while (temp){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM