创建链表-头插法和尾插法

来源:互联网 发布: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),否则外部引用不到,出段错误。