头文件
#ifndef MYLIST_H
#define MYLIST_H
#endif // MYLIST_H
typedef struct _Node
{
int data;
struct _Node *next;
}Node;
Node *creatList();
void traverList(Node *head);
int strlenList(Node *head);
void insertList(Node *head,int data);
Node *searchList(Node *head,int data);
void deleteList(Node *head,Node *pfind);
void popSortList(Node *head);
void desteryList(Node *head);
void reverseList(Node *head);
源文件
#include "mylist.h"
#include <stdio.h>
Node *creatList() //创建
{
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
return head;
}
void traverList(Node *head)//遍历
{
head = head->next;
while(head)
{
printf("%d\n",head->data);
head = head->next;
}
}
int strlenList(Node *head)//求长
{
int len = 0;
head = head->next;
while(head)
{
len++;
head = head->next;
}
return len;
}
void insertList(Node *head,int data)//插入
{
Node *cur = (Node *)malloc(sizeof(Node));
cur->data = data;
cur->next = head->next;
head->next = cur;
}
Node *searchList(Node *head,int data) //查找
{
head = head->next;
while(head)
{
if(head->data == data)
return head;
head = head->next;
}
return NULL;
}
void deleteList(Node *head,Node *pfind) //删除
{
while(head->next != pfind)
{
head = head->next;
}
head->next = pfind->next;
free(pfind);
}
void popSortList(Node *head) /*交换数据排序*/
{
Node *p,*q;
int len = strlenList(head);
for(int i = 0;i<len-1;i++)
{
p = head->next;
q = p->next;
for(int j =0;j<len-1-i;j++)
{
if(p->data > q->data)
{
p->data ^= q->data;
q->data ^= p->data;
p->data ^= q->data;
}
p = p->next;
q = p->next;
}
}
}
void popSortList2(Node *head) /*交换结点排序*/
{
Node *p,*q,*pre;
int len = strlenList(head);
for(int i = 0;i<len-1;i++)
{
pre = head;
p = head->next;
q = p->next;
for(int j =0;j<len-1-i;j++)
{
if(p->data > q->data)
{
pre->next = q;
p->next = q->next;
q->next = p;
pre = q;
q = p->next;
continue;
}
pre = pre->next;
p = p->next;
q = q->next;
}
}
}
void desteryList(Node *head)//销毁
{
while(head)
{
Node *t = head->next;
free(head);
head = t;
}
}
void reverseList(Node *head) /*逆序链表*/
{
Node *h = head->next;
head->next = NULL;
Node *t;
while(h)
{
t = h->next;
h->next = head->next;
head->next = h;
h = t;
}
}
测试代码
#include <stdio.h>
#include <time.h>
#include "mylist.h"
int main(int argc, char *argv[])
{
srand(time(NULL));
Node *head = creatList();
for(int i = 0;i < 10;i++)
{
insertList(head,rand()%12);
}
traverList(head);
putchar(10);
printf("%d\n",strlenList(head));
Node *find = searchList(head,10);
printf("%d\n",find->data);
deleteList(head,find);
printf("%d\n",strlenList(head));
printf("------------------\n");
popSortList2(head);
traverList(head);
printf("------------------\n");
reverseList(head);
traverList(head);
desteryList(head);
return 0;
}