码迷,mamicode.com
首页 > 其他好文 > 详细

SinglyLinkList 3 -- Insert

时间:2015-09-09 18:55:38      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

Implement:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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

node *LinkList;
void display(node *list);
node *insert(node *list, int data);

void main()
{
    LinkList = insert(LinkList, 1);
    display(LinkList);
    LinkList = insert(LinkList, 2);
    display(LinkList);
}

node* create(node *list)
{
    list = (node *)malloc(sizeof(node));
    return list;
}

void display(node *list)
{
    while(list)
    {
        printf("address:%d, data: %d, its next: %d\n", list, list->data, list->next);
        list = list->next;
    }
}

node* insert(node *list, int data)
{
    node* head = list;

    /* If the list is empty*/
    if(list==NULL)
    {
        list = (node *)malloc(sizeof(node));
        list->data = data;
        list->next = NULL;
        
        head = list;
        return head;
    }    
/* Iterate through the list till we encounter the last node. */ while(list->next != NULL) { list = list->next; } /* Allocate memory for the new node and put data in it */ list->next = (node *)malloc(sizeof(node)); list = list->next; list->data = data; list->next = NULL; return head; }


Procedure Figure:

技术分享

 

Output:

gcc SinglyLinkList3.c -lcurses -o SinglyLinkList3 
./SinglyLinkList3address:19963920, data: 1, its next: 0
address:19963920, data: 1, its next: 19963952
address:19963952, data: 2, its next: 0

 

Remark:

1) Because the code "(node *)malloc(sizeof(node));" will return a node with default value, that‘s why there is no Initialize function implemented.

2) Because C Language doesn‘t support the "&" address-of operator in parameters, so we need to restore the head pointer and return it in Insert function.

3) There will be 2 different operations between empty list and non-empty list.

SinglyLinkList 3 -- Insert

标签:

原文地址:http://www.cnblogs.com/Aegis-Liang/p/4795280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!