本文是继上两篇之后的博客:主要展示对链表中的数字,使用冒泡法进行排序;
# include<stdio.h>
# include<math.h>
# include<stdlib.h>
using namespace std;
typedef struct node
{
int data;
struct node * next;
}Node;
Node * creat_list_first()
{
Node * head = (Node *)malloc(sizeof(Node));
head->next = NULL;
int data;
printf("请输入节点数据:\n");
scanf("%d", &data);
while (data)
{
Node * cur = (Node *)malloc(sizeof(Node));
cur->data = data;
cur->next = head->next;
head->next = cur;
scanf("%d", &data);
}
return head;
}
Node * insert_list_end()
{
Node * head = (Node *)malloc(sizeof(Node));
head->next = NULL;
Node * phead = head;
printf("请输入节点数字:\n");
int data;
scanf("%d", &data);
while (data)
{
Node * cur = (Node *)malloc(sizeof(Node));
cur->next = NULL;
cur->data = data;
phead->next = cur;
phead = cur;
scanf("%d", &data);
}
return head;
}
void show_list(Node * head)
{
Node * p = head->next;
while (p)
{
printf("%d\n", p->data);
p = p->next;
}
}
int len_list(Node *head)
{
Node * phead = head->next;
int count = 0;
while (phead)
{
count++;
phead = phead->next;
}
return count;
}
int search_node_loc(Node * head, int search_data)
{
Node * phead = head->next;
int loc = 1;
while (search_data != phead->data)
{
loc++;
phead = phead->next;
}
return loc;
}
Node * search_node_dizhi(Node * head,int search_data)
{
Node * phead = head->next;
while (phead)
{
if (phead->data == search_data)
{
break;
}
phead = phead->next;
}
return phead;
}
void delete_node(Node * head, Node * delete_node)
{
Node * loc = delete_node;
while (head->next != loc) head = head->next;//此处说明是待查找数据的前一项节点;
head->next = loc->next;
}
void pop_sort(Node*phead, int len)
{
Node * cur = NULL;
int temp = 0;
for (int i = 0; i < len - 1; i++)
{
cur = phead->next;
for (int j = 0; j < len - 1 - i; j++)
{
if (cur->data > cur->next->data)
{
temp = cur->data;
cur->data = cur->next->data;
cur->next->data = temp;
}
cur = cur->next;
}
}
}
int main()
{
Node * head = insert_list_end();
show_list(head);
printf("链表长度:%d\n", len_list(head));
printf("查找数据在%d\n", search_node_loc(head, 4));
delete_node(head, search_node_dizhi(head, 4));
show_list(head);
printf("after pop sort \n");
pop_sort(head, len_list(head));
show_list(head);
return 0;
}