单链表的实现思想和双指针的应用方法在前面博客中都已阐述,在本文将实现双指针实现单链表的初始化,插入,删除,打印。
【测试代码1】
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}node_t;
//创建头结点
node_t * create()
{
node_t *head = (node_t *)malloc(sizeof(node_t));
head->next = NULL;
return head;
}
void insert(node_t **list, int data)
{
node_t *pnode = (node_t *)malloc(sizeof(pnode));
pnode->data = data;
pnode->next = NULL;
if(*list == NULL)
{
*list = pnode;
}
else
{
node_t *p =*list;
while(p->next != NULL)
{
p = p->next;
}
p->next = pnode;
}
}
void remove(node_t **list, int data)
{
node_t *p =( *list);
if(p ->next== NULL)
return ;
while(p->next->data != data)
p = p->next;
if(p->next == NULL)
printf("no data");
if (p->next->data == data)
p->next = p->next->next;
}
void print(node_t **list)
{
node_t *p = (*list)->next;
if(!p)
return;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}
void main()
{
node_t *head;//链表头结点
node_t **list;//链表头指针
head = create();
list =& head;//令链表头指针指向头结点
insert(list,1);
insert(list,2);
insert(list,3);
insert(list,4);
insert(list,5);
insert(list,6);
printf("after insert data, the list data is:\n");
print(list);
printf("\n");
printf("remove data 6, the list data is:\n");
remove(list,6);
print(list);
}
【输出结果】
这里采用尾部插入,所以头指针始终指向头结点,双指针的用处就是你可以改变其头结点后面的内容,而不会改变头指针的位置,如果是前部插入的话,需要不断变化头结点的位置,程序会有所区别。
【测试代码2】
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}node_t;
//使得头指针指向头结点
node_t * create()
{
node_t *head = (node_t *)malloc(sizeof(node_t));
head->next = NULL;
return head;
}
void insert_front(node_t **list, int data)
{
node_t *pnode = (node_t *)malloc(sizeof(pnode));
pnode->data = data;
pnode->next = (*list)->next;
(*list)->next = pnode;
}
void remove(node_t **list, int data)
{
node_t *p =( *list);
if(p ->next== NULL)
return ;
while(p->next->data != data)
p = p->next;
if(p->next == NULL)
printf("no data");
if (p->next->data == data)
p->next = p->next->next;
}
void print(node_t **list)
{
node_t *p = (*list)->next;
if(!p)
return;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}
void main()
{
node_t *head;
node_t **list;
head = create();
list =& head;
insert_front(list,1);
insert_front(list,2);
insert_front(list,3);
insert_front(list,4);
insert_front(list,5);
insert_front(list,6);
printf("after insert data, the list data is:\n");
print(list);
printf("\n");
printf("remove data 6, the list data is:\n");
remove(list,6);
print(list);
}
【输出结果】
时间: 2024-10-10 22:17:15