数据结构2 - 链表

一、链表是一种常见的重要的数据结构。

它是动态地进行存储分配的一种结构。

它可以根据需要开辟内存单元。

链表有一个“头指针”变量,以head表示,它存放一个地址。该地址指向一个元素。

链表中每一个元素称为“结点”,每个结点都应包括两个部分:一为用户需要用的实际数据,二为下一个结点的地址。

因此,head指向第一个元素:
第一个元素又指向第二个元素;
……,
直到最后一个元素,该元素不再指向其它元素,它称为“表尾”,
“表尾”的地址部分放一个“NULL”(表示“空地址”),链表到此结束。

二、单向链表

链表的各类操作包括:

 1. 创建

 2. 输出

 3. 插入(无序、有序)

 4. 删除

 5. 反序

 6. 排序(选择、插入、冒泡)
//
//  main.c
//  C语言单向链表
//
//  Created by zhengbing on 2017/5/16.
//  Copyright © 2017年 zhengbing. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h> // malloc 可以开辟指定大小的内存空间

// 是否需要补齐,要看开辟的总空间是不是最大成员变量所占内存的倍数
// 定义一个节点(node)的结构体
struct Student {
    char name[20];              // 存储学生姓名
    int age;                    // 存储学生年龄
    struct Student * next;      // 指向下一个节点
};

// 创建一个新节点并返回其地址
struct Student * newNode(){

    // 开辟一个大小为 32 的地址空间,并强制转换为(struct Student *)的指针
    struct Student * stu = (struct Student *)malloc(sizeof(struct Student));

    printf("请输入姓名:\n");
//    scanf("%s", &stu->name[0]); // 给姓名赋值(数组名就表示首地址)
    scanf("%s", stu->name); // 给姓名赋值(数组名就表示首地址)

    printf("请输入年龄:\n");
    scanf("%d", &stu->age); // 给年龄赋值

    stu->next = NULL;       // 默认尾指针 = NULL
    return stu;
}

struct Student * createList(){
    struct Student * head = newNode();
    struct Student * preNode = head; // 最开始的前指针为头指针
    struct Student * node = newNode();

    // 当新建的节点age != 0 的时候,就串联到链表上去
    while (node->age != 0) {
        preNode->next = node;   // 1.让前节点指向新节点
        preNode = node;         // 2.让最后一个节点成为新的前节点
        node = newNode();       // 3.继续创建新节点
    }
    return head;
}

void printList(struct Student * head){
    printf("=====================\n");

    struct Student * temp = head;
    while (temp != NULL) {
        printf("姓名:%s \n",temp->name);
        printf("年龄:%d \n",temp->age);
        printf("下一个节点地址:%p \n",temp->next);
        temp = temp->next;
    }
}

int main(int argc, const char * argv[]) {

    struct Student stu  = * createList();
    printList(&stu);
    return 0;
}

三、双向链表
四、循环链表

posted @ 2017-04-25 23:14  磨刀石  阅读(213)  评论(0编辑  收藏  举报