单链表的建立、插入、读取操作

来源:互联网 发布:淘宝的评价管理在哪里 编辑:程序博客网 时间:2024/06/02 02:31


---------------------sll_node.h---------------------------------------

#ifndef _SLLNODE_#define _SLLNODE_typedef struct NODE{struct NODE *link;int value;} Node;#endif


---------------------Source.cpp---------------------------------------

/*新建一个单链表,链表的建立和读取操作*/#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include "sll_node.h"#pragma warning(disable:4996)Node *create(Node *head);void print(Node* head);Node *sll_insert(Node *head, int new_value);int main(){Node *head;head = NULL;head = create(head); /*建立链表*/head = sll_insert(head, 12);/*链表的插入操作*/print(head);/*打印链表*/system("pause");return 0;}Node *create(Node *head){Node *p1, *p2;int i = 1;p1 = (Node*)malloc(sizeof(Node));p2 = p1;printf("请输入值,值小于等于0结束,值存放于p1_ADDR = %d\n", p1);scanf("%d", &p1->value);/*输入节点的值*/p1->link = NULL;while (p1->value > 0){if (head == NULL)head = p1; /*注意p1和p1->link 地址的区别*/elsep2->link = p1;p2 = p1;p1 = (Node*)malloc(sizeof(Node));/*下一个新节点*/i++;printf("请输入值,值小于等于0结束,值存放于p%d_ADDR = %d\n",i,p2);scanf("%d", &p1->value);}free(p1);p1 = NULL;p2->link = NULL;printf("链表输入结束!\n");return head;}void print(Node *head){Node *temp;temp = head;printf("链表存入的值为:\n");while (temp != NULL){printf("%6d\n", temp->value);temp = temp->link;}printf("打印结束!");}Node* sll_insert(Node *head, int new_value){Node *current = head;Node *previous = current;Node *new_node;while (current != NULL && current->value < new_value){previous = current;current = current->link;}new_node = (Node*)malloc(sizeof(Node));if (new_node != NULL){new_node->value = new_value;new_node->link = current;previous->link = new_node; //若previous未被初始化,则会出现潜在的错误}return head;}


0 0