#include<iostream>
#include<stdio.h>
#include <windows.h>
#include<string>
#include<vector>
using namespace std;
typedef struct list{
struct list *next;
int data;
}list;
list *head;
void list_creat() //這個地方head沒有初始化,分配內存,統計指針不能作爲參數傳遞過來
{
head = (list*)malloc(sizeof(list));
head->next = NULL;
head->data = 0;
}
void list_insert(list *list_head ,int data_t) //頭插
{
list *p1;
p1 = (list*)malloc(sizeof(list));
p1->data = data_t;
p1->next = list_head->next;
head->next = p1;
}
void list_insert_tail(list *list_head, int data_t) //尾插
{
list *p,*temp1;
list *temp;
temp = (list*)malloc(sizeof(list));
temp1 = (list*)malloc(sizeof(list));
p = list_head->next;
while (p != NULL)
{
temp1 = p;
p = p->next;
}
temp1->next=temp;
temp->data = data_t;
}
void list_delete(list *list_head,int i) //刪除第i個鏈表節點
{
list *p=NULL;
list *temp=NULL;
p = head->next;
if (i == 1)
{
list_head->next = p->next;
free(p);
}
else
{
i--;
while (--i)
{
p= p->next;
}
temp = p->next;
p->next = temp->next;
free(temp);
}
}
int list_len(list *list_head) //求鏈表長度
{
int len = 0;
list *p=NULL;
p = list_head->next;
while (p != NULL)
{
len++;
p = p->next;
}
return len;
}
void list_sort(list *list_head,int len) //利用冒泡給鏈表排序
{
list *p=NULL;
int temp_data;
p = list_head->next;
int i = 0,j;
for (i = 0; i < len-1; i++)
{
p = list_head->next;
for (j = 0; j < len-i - 1; j++)
{
if (p->data > p->next->data) //數據交換雖然簡單,但會有內存搬運,可以用指向變換
{
temp_data = p->next->data;
p->next->data = p->data;
p->data = temp_data;
}
p = p->next;
}
}
}
void list_reverse(list *list_head) //鏈表逆序
{
list *p=NULL;
p = list_head->next;
list_head->next = NULL;
for (p; p != NULL; p = p->next)
{
list_insert(list_head, p->data); //從頭開始使用頭插法,實現逆序問題
}
}
void print_list(list *list_head)
{
list *temp = list_head->next;
while (temp != NULL)
{
cout << temp->data;
temp = temp->next;
}
cout << endl;
}
void list_destroy(list *head_list)
{
list *p=NULL;
while (head_list)
{
p = head_list->next;
free(head_list);
head_list = p;
}
}
int main()
{
int len;
list_creat();
list_insert(head, 1);
list_insert(head, 2);
list_insert(head, 3);
list_insert(head, 4);
print_list(head);
len = list_len(head);
list_sort(head, len);
print_list(head);
list_delete(head,2);
print_list(head);
list_reverse(head);
print_list(head);
list_insert_tail(head,5);
print_list(head);
list_destroy(head);
system("pause");
return 0;
}