【链表】链表的操作(二)

上一篇写了链表的基本概念,这一篇通过在C++上建链表,实现基本的输入输出,筛选功能进行测试。

代码:

#include <iostream>
#include<stdio.h>
#include <stdlib.h>
using namespace std;
#define OK 1
#define ERROR 0

typedef struct Node{
    int value;
    Node *next;
};

Status GetElem(Node *L, int i, int *e){
    Node *p;
    int j;
    p = L;
    j=0;
    while(p && j<i){
        p = p->next;
        ++j;
    }
    if(!p || j>i){
        return ERROR;
    }
    *e = p->value;
    return OK;
}

int main()
{
    int n;
    cin>>n;
    Node *head = NULL;
    Node *p = NULL;
    Node *q = NULL;
    for(int i=0;i<n;i++){   //输入链表,头指针为head
        q = new Node;
        cin>>q->value;
        if(head==NULL){
            head = q;
            p = head;
        }else{
            p->next = q;
            p = p->next;
        }
    }
    p->next=NULL;
    q = head;
    while(q!=NULL){   //对输入的链表正序输出
        cout<<q->value<<" ";
        q = q->next;
    }
    int e;
    int a=GetElem(head,1,&e); //查找序号为1链表元素
    cout<<a<<" "<<e<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_chuxuezhe/article/details/81984281