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;
}