动态链表:带头节点
定义
typedef struct _Node
{
int data;
struct _Node * next;
}Node;
创建链表
Node * createList()
{
Node * head = (Node *)malloc(sizeof(Node));
if(NULL == head)
exit(-1);
head->next = NULL;
return head;
}
求长
int lenList(Node * head)
{
head = head->next;
int len = 0;
while(head)
{
len++;
head = head->next;
}
return len;
}
遍历
//遍历
void traverseList(Node * head)
{
head = head->next;
while(head)
{
printf("%d\n",head->data);
head = head->next;
}
}
查找节点
//查找
Node * searchList(Node * head,int find)
{
head = head->next;
while(head)
{
if(head->data == find)
break;
head = head->next;
}
}
头插法
//头插法 让新来的节点有所指向
void insertHeadList(Node* head,int data) {
Node * cur = (Node *)malloc(sizeof(Node));
cur->data = data;
cur->next = head->next;
head->next = cur;
}
尾插法
//尾插法
void insertTailList(Node * head, int data) {
Node *cur = (Node *)malloc(sizeof(Node));
cur->data= data;
while(head->next) {
head = head->next;
}
head->next = cur;
cur->next = NULL;
}
删除节点
//删除节点
void deleteNodeList(Node * head, Node * pFind)
{
if(pFind->next != NULL)
{
while (head->next != pFind)
{
head = head->next;
}
head->next = pFind->next;
pFind = NULL;
}
else
{
pFind->data = pFind->next->data;
pFind->next = pFind->next->next;
}
}
冒泡排序
void popSortList(Node *head)
{
int len = lenList(head);
head = head->next;
Node *p ,*q;
for(int i=0;i<len-1;i++)
{
p = head;
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; // 不是q->next
}
}
}
冒泡排序优化
//排序优化
void popSortList(Node *head)
{
int len = lenList(head);
//head = head->next;
Node *p ,*q, *prep,*t;
for(int i=0;i<len-1;i++)
{
prep = head;
p = head->next;
q = p->next;
for(int j=0;j<len-1-i;j++) // j<len-1-i
{
if(p->data > q->data)
{
prep->next = q;
p->next = q->next;
q->next = p;
t = p;
p = q;
q = t;
}
prep = prep->next;
p = p->next;
q = q->next;
}
}
}
链表逆置
//逆置链表,先割裂后头插
void reverList(Node * head)
{
Node *cur = head->next;
head->next = NULL;
Node *t;
while(cur)
{
t = cur;
cur = cur->next;
t->next = head->next;
head->next = t;
}
}
销毁链表
void destroyList(Node * head)
{
Node *t;
while(head)
{
t = head;
head = head->next;
free(t);
}
}
main
Node * head = createList();
srand(time(NULL));
for(int i=0;i<5;i++)
{
insertList(head,rand()%10);
}
int len = lenList(head);
printf("len = %2d\n",len);
insertHeadList(head,300);
insertTailList(head,100);
insertTailList(head,101);
popSortList(head);
travereList(head);
return 0;
运行结果:
len = 5
0 1 4 6 6 100 101 300