#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BOOL int
#define FALSE 0
#define TRUE 1
typedef struct _Node{
int value;
struct _Node *next;
}Node;
BOOL insert(Node **root,int new_value);
void print(Node *root);
int main (int argc, const char * argv[])
{
Node *root;
insert(&root, 22);
insert(&root, 23);
insert(&root, 12);
insert(&root, 26);
print(root);
int a = 10;
int *p = &a;
printf("%d,%d",p,*p);
return 0;
}
BOOL insert(Node **root,int new_value){
Node *current;
Node *previous;
Node *new;
//root指的就是链表首节点的指针的地址,
//现在current指向root指向的内容,就是链表指针,也就是链表首节点的地址,
//如果改变current的值只能影响到链表中的内容,不能影响到链表首地址的地址。
//如果想改变链表首地址的地址,只能用*root。
current = *root;
previous = NULL;
while (current != NULL && current->value < new_value) {
previous = current;
current = current->next;
}
new = (Node *)malloc(sizeof(Node));
if (new == NULL) {
return FALSE;
}
new->value =new_value;
new->next = current;
if (previous == NULL) {
*root = new;
}
else
previous->next = new;
return TRUE;
}
void print(Node *root){
while (root != NULL) {
printf("%d\n",root->value);
root = root->next;
}
}
实现了添加和打印出链表内容的insert和print函数。
因为链表是有序的,所以如果插入的元素是最小的,那么就要改变链表首元素的地址。如果insert参数是Node*类型的,那么只能改变
链表的内容,而不能改变链表首元素地址。