C 单向链表:创建、插入、遍历、求长、查找、删除、逆置、排序、销毁
链表节点定义,为了方便,还是和之前一样
typedef struct node
{
int data; //数据域:存储数据
struct node * next; //指针域:指向下一个节点(指向谁,就保存了谁的地址)
}Node;
当然,复杂的数据也可以这么写:
typedef struct data
{
char name[200];
int age;
char score[200];
char *ptr;
//......
}Data;
typedef struct node
{
Data data; //数据域:存储数据
struct node * next; //指针域:指向下一个节点(指向谁,就保存了谁的地址)
}Node;
一、创建
真正意义上的创建链表,就是创建一个空链表。
Node * createList()
{
Node *head = (Node*)malloc(sizeof(Node));
if(NULL == head)
exit(-1);
head->next = NULL;
return head;
}
二、插入
插入操作,本质上就是头插法!
void insertList(Node * head, int inputData)
{
Node *ptr = (Node *)malloc(sizeof(Node));
if (NULL == ptr)
exit(-1);
ptr->data = inputData;
ptr->next = head->next;
head->next = ptr;
}
三、遍历
void traverseList(Node * head)
{
head = head->next;
while (head)
{
printf("%-3d", head->data);
head = head->next;
}
}
四、求长
int lengthList(Node *head)
{
int len = 0;
head = head->next;
while (head)
{
len++;
head = head->next;
}
return len;
}
五、查找
Node * searchList(Node * head, int searchData)
{
head = head->next;
while (head)
{
if (searchData == head->data)
break;
head = head->next;
}
return head;
}
六、删除
void deleteNode(Node * head, Node * pdst)
{
if (NULL == pdst->next)
{
while (head->next != pdst)
head = head->next;
head->next = pdst->next;
free(pdst);
pdst = NULL;
}
else
{
Node *tmp = pdst->next