数据结构链表 --头节点链表复习

来源:互联网 发布:发现旅行靠谱吗 知乎 编辑:程序博客网 时间:2024/06/05 04:37

1、头节点式得链表操作;
(1)创建链表的头节点;
(2)创建新的节点;

3)进行数据的插入;数据的插入有三种插入方式,头插,尾插,任意位置的插入,最重要的插入操作是任意位置的插入;改进版本的任意位置插入使用for循环

int Insert_pos(Node*head,int pos,int data){    if(head == NULL || pos < 1)    return -1;    Node*tmp = head;    int i;    for(i= 0; i < pos -1;i++)    {        if(tmp == NULL)            break;        tmp = tmp->next;    }    Node *node = (Node*)malloc(sizeof(Node)/sizeof(char));    if(node == NULL)        return -1;    if(tmp == NULL)    {        printf("出现越界\n");        return;    }    node->data = data;    node->next = tmp->next;    tmp->next  = node;    return 0;   }

// 原版使用while循环int Insert_Pos(Node* head, int pos, ElementType data){    if (head == NULL || pos < 1)    {        printf ("参数有误\n");        return ERROR;    }    Node *tmp = head;    int k = 0;    while (tmp != NULL && k < pos -1)    {        tmp = tmp->next;        k++;    }    if (tmp == NULL)  // 越界    {        printf ("插入位置越界\n");        return ERROR;    }    Node *node = (Node*)malloc(sizeof(Node)/sizeof(char));    if (node == NULL)    {        return ERROR;    }    node->data = data;    node->next = tmp->next;    tmp->next = node;    return OK;}

俩种循环的方式相对来说,for循环相对来说简单易读易操作


头文件函数

#include <stdio.h>#include "2.头文件.h"#include <stdlib.h>
Node *Creat(){    Node *head =(Node*)malloc(sizeof(Node)/sizeof(char));    if(head == NULL)        return NULL;    head->next =NULL;    return head;}int Insrt_head(Node*head,int data){    if(head == NULL)        return -1;    Node*node= (Node*)malloc(sizeof(Node)/sizeof(char));    if(node == NULL)        return -1;    node->data = data;    node->next = head->next;    head->next = node;    return 0;}void display(Node*head)   // 打印遍历函数时通过使用中间变量tmp进行操作{    if(head == NULL)        return ;    Node*tmp = head;    while(tmp)    {        int count = 0;        /* if(count++ %4 ==0)            putchar('\n'); */        count++ %4 ==0; /* && putchar('\n'); */        printf ("%8d", tmp->data);        tmp = tmp->next;    }    printf("\n");}int Insert_pos(Node*head,int pos,int data){    if(head == NULL || pos < 1)    return -1;    Node*tmp = head;    int i;    for(i= 0; i < pos -1;i++)    {        if(tmp == NULL)            break;        tmp = tmp->next;    }    Node *node = (Node*)malloc(sizeof(Node)/sizeof(char));    if(node == NULL)        return -1;    if(tmp == NULL)    {        printf("出现越界\n");        return;    }    node->data = data;    node->next = tmp->next;    tmp->next  = node;    return 0;   }

循环链表就是构造链表环,就是将头节点链表最后节点的NULL更改指向头节点(非空表的情况);
空表的情况下,就是将头节点指向自己


原创粉丝点击