创建链表-头插法和尾插法
来源:互联网 发布:c网络编程那本书好 编辑:程序博客网 时间:2024/05/18 01:28
1,头插法和尾插法
新增节点插入的位置不同,头插法是在头结点之后,尾插法只在链表末尾。
2,代码
#include <stdio.h>typedef struct ListNode{int data;struct ListNode *next;}ListNode, *pListNode;void addHead_createList(ListNode **head, int n) //头插法{int i;*head = (ListNode *)malloc(sizeof(ListNode));(*head) ->next = NULL;for(i = 0; i < n; i++){ListNode *p = (ListNode *)malloc(sizeof(ListNode));scanf("%d", &(p->data));p->next = (*head)->next;(*head)->next = p;}}void addTail_createList(ListNode **head, int n) //尾插法{int i;ListNode *r;*head = (ListNode *)malloc(sizeof(ListNode));(*head)->next = NULL;r = *head;for(i = 0; i < n; i++){ListNode *p = (ListNode *)malloc(sizeof(ListNode));scanf("%d", &(p->data));p->next =NULL;r->next = p;r = p;}}void showList(ListNode **head){ListNode *p = (*head)->next;while(p){printf("%d ", p->data);p = p->next;}printf("\n");}void destoryList(ListNode **head){ListNode *p = (*head)->next;ListNode *tmp;while(p){tmp = p;p = p->next;free(tmp);}(*head)->next = NULL;}int main(){int n;ListNode *head = NULL;scanf("%d", &n);addHead_createList(&head, n);showList(&head);destoryList(&head);addTail_createList(&head, n);showList(&head);destoryList(&head);return 0;}
3,结果
4,注意
这里有个陷阱,函数外部(比如addHead_createList)外需要使用head来输出链表内容,创建的时候传值应该是指针的指针(ListNode **head),否则外部引用不到,出段错误。
阅读全文
0 0
- 头插法和尾插法创建链表
- 创建链表-头插法和尾插法
- 算法学习-链表创建,头插法和尾插法
- 头插法和尾插法创建单链表
- 头插法和尾插法创建单链表
- 链表创建 和 倒置
- 创建和删除链表
- 数据结构学习(二)——单链表的操作之头插法和尾插法创建链表
- 链表的创建头插法和尾插法(有无头节点)
- 数据结构学习(二)——单链表的操作之头插法和尾插法创建链表
- 数据结构学习(二)——单链表的操作之头插法和尾插法创建链表
- 数据结构 -- 单链表创建之头插法和尾插法
- 创建单链表的头插法和尾插法
- 创建链表和显示链表
- 链表创建和链表遍历
- 链表创建,显示,删除和倒置
- 双向链表的创建和删除
- 链表的创建和遍历算法
- 深入浅出讲解:php的socket通信
- 树状数组求逆序对
- Java笔试题解-流程控制(2)
- SpringMVC接收前台传递过来的值的方法
- Leetcode Largest Rectangle in Histogram
- 创建链表-头插法和尾插法
- mysql 用一个表更新另一个表
- Java IO
- ssl和tsl区别
- Mac/Windows下,Python3安装Scrapy模块
- PHP 开发环境搭建
- 一个测试工程师的职业生涯感悟
- javassist 动态生成WebService
- codeM题目-寻找最小difference