#include "stdafx.h"
#include<iostream>
#include<queue>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Node,*List;
List createList(int N)//建立链表
{
List head = (List)malloc(sizeof(Node));
head->data = 0;
head->next=NULL;
int count = 0;
List p = head;
while(count<N)
{ count++;
List s = (List)malloc(sizeof(Node));
s->data = count;
s->next = NULL;
p->next = s;
p = s;
}
return head;
}
void traverse(List head)//遍历链表
{
if(head == NULL)
{
return;
}
List p = head->next;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
bool sort(List head)//对链表进行排序
{
if(head == NULL)
return false;
List pre,p,tailor,header;
pre = head->next;
if(pre==NULL)
return false;
header = pre;//记住第一个节点
tailor = NULL;//tailor指向已排序序列的第一个节点
while(tailor != header->next)//如果只剩下一个最后一个未排序节点,那么排序完成
{
pre = header;//初始化pre,和p指向前个节点
p = pre->next;
while(p!=tailor)//这个就相当于冒泡排序里面的j <n-i
{
if(pre->data > p->data)//把大的值往后面移动
{
int tmp = pre->data;
pre->data = p->data;
p->data = tmp;
}
pre = p;//移动指针
p = p->next;
}
tailor = pre;//有序区新加入一个节点,所以tailor往前移动一个位置
}
return true;
}
void deleteNode(List head, int index)//删除第index个节点
{
if(head == NULL)
return;
List pre, p;
pre = p = head;
int count = 0;
while(p!=NULL && count<index)
{
pre = p;
p = p->next;
count++;
}
//cout<<count<<endl;
if(p==NULL)
{
cout<<"illegal positioin!"<<endl;
return;
}
pre->next = p->next;
free(p);
}
bool insert(List head, int element,int index)//把data=element的节点插在链表的第index个位置上
{
if(head == NULL || head->next==NULL)
return false;
List pre,p;
pre = head;
p = head;
int count = 0;
while(p != NULL&& count<index)
{
pre = p;
p = p->next;
count++;
}
if(count == index)
{
List no = (List)malloc(sizeof(Node));
no->data = element;
no->next = NULL;
no->next = p;
pre->next = no;
return true;
}
else
{
cout<<"illegal position"<<endl;
}
return false;
}
int main()
{
int N = 10;
List head = createList(N);
traverse(head);
insert(head, 20, 2);
insert(head, 15, 2);
//deleteNode(head,20);
traverse(head);
sort(head);
traverse(head);
getchar();
return 0;
}