代码改变世界

面试题2:单链表的创建、打印

2016-03-25 21:29  Keiven_LY  阅读(405)  评论(0编辑  收藏  举报

题目描述:

编程实现一个单链表的建立、打印

单链表的创建功能函数

/****创建含有n个结点的单链表******/
Node *CreateListHead(int n) 
{
    Node *head;
    head=(Node *)malloc(sizeof(Node)); /*创建头结点*/
    Node *q = head;

    /* 初始化随机数种子 */
    srand(time(0));  //srand函数在stdlib.h头文件中,time函数在time.h头文件中

    for(int i=0; i < n; i++)
    {
        Node *p = (Node *)malloc(sizeof(Node));
        p->data = rand()%100+1;  //随机生成100以内的数字 
        p->next = q->next;
        q->next = p;
        q = p;
    }
    q->next = NULL;

    return head;
}

单链表的打印功能函数

/****打印单链表******/
void print(Node *head)
{
    Node *p;
    if(head->next==NULL)
    {
        cout << "The LinkList is Empty !" <<endl;
        return;
    }
    p=head->next;
    while(p!=NULL)
    {
        cout << p->data << " " ;
        p=p->next;
    }
}

完整的可执行程序:

#include<iostream>
#include<stdlib.h> 
#include<time.h>

using namespace std;


typedef struct node
{
    int data;
    struct node *next;
}Node;

/****创建含有n个结点的单链表******/
Node *CreateListHead(int n) 
{
    Node *head;
    head=(Node *)malloc(sizeof(Node)); /*创建头结点*/
    Node *q = head;

    /* 初始化随机数种子 */
    srand(time(0));  //srand函数在stdlib.h头文件中,time函数在time.h头文件中

    for(int i=0; i < n; i++)
    {
        Node *p = (Node *)malloc(sizeof(Node));
        p->data = rand()%100+1;  //随机生成100以内的数字 
        p->next = q->next;
        q->next = p;
        q = p;
    }
    q->next = NULL;

    return head;
}

/****打印单链表******/
void print(Node *head)
{
    Node *p;
    if(head->next==NULL)
    {
        cout << "The LinkList is Empty !" <<endl;
        return;
    }
    p=head->next;
    while(p!=NULL)
    {
        cout << p->data << " " ;
        p=p->next;
    }
}

int main()
{
    Node *SingleLinkList;
    int length;
    cout << "Please input the length of LinkList: " <<endl;
    cin >> length;
    SingleLinkList = CreateListHead(length);
    cout << "The new created LinkList as below: " <<endl;
    print(SingleLinkList);
    cout << endl;

    system("pause");
    return 0;
}

运行结果: