链表

2017-07-21 14:59:35

writer:pprp

好久没有写链表了,有点怀念,之前写的链表比较全,但是大部分都是一步一步照着别人的代码写的,这次是第一次独立写链表;

功能不多,只有创建指定数量的链表和遍历输出链表;

代码如下:

#include <iostream>

using namespace std;

struct List
{
    int val;
    List* next;
    List* pre;
};

List * create(List *head)
{
    int num;
    int tmpval;
    cout << "Enter the number of element you want to create:" << endl;
    cin >> num;
    List *p;
    head = new List();
    cin >> tmpval;
    head->val = tmpval;
    head->next = NULL;
    for(int i = 0 ; i < num-1 ; i++)
    {
           cin >> tmpval;
            p = head;
            while(p->next!=NULL)
            {
                p = p->next;
            }
            List *tmp = new List();
            p->next = tmp;
            tmp->val = tmpval;
            tmp->next = NULL;
    }
    return head;
}

void display(List *head)
{
    int cnt = 0;
    if(head == NULL)
        cout <<"Nothing in here!" << endl;
    else
    {
        
        List* p = head;
        while(p!=NULL)
        {
            cout << "Case" << ++cnt <<": " <<p->val<<endl;
            p = p->next;
        }
        
    }
}
int main()
{
     List*head = NULL;
    head = create(head);
    cout <<"display:" <<endl;
    display(head);
    return 0;
}

 

posted @ 2017-07-21 15:03  pprp  阅读(214)  评论(0编辑  收藏  举报