单链表的正向排序,就是插入数据时就按从小到大排序。
代码有注释很容易理解的:
//单链表的正向排序 node *InsertSort(void) { int data = 0; struct node *head = NULL; struct node *New, *Cur, *Pre; while(1) { printf("please input the data: "); scanf("%d", &data); if(0 == data) //输入0结束 { break; } New = (struct node*)malloc(sizeof(struct node)); New->data = data; //新分配一个node节点 New->next = NULL; if(NULL == head) //第一次循环时对头节点赋值 { head = New; continue; } if(New->data <= head->data) //head之前插入节点 { New->next = head; head = New; continue; } Cur = head; while(New->data > Cur->data && NULL != Cur->next) { //找到需要插入的位置 Pre = Cur; Cur = Cur->next; } if(Cur->data >= New->data) //位置在中间 { //把New节点插入到pre和cur之间 Pre->next = New; New->next = Cur; } else //末尾位置 { //把new节点插入到cur之后 Cur->next = New; } } return head; }
程序代码如下:
//判断单链表是否存在回路 //如果存在,start存放回环开始的节点 bool IsLoop(node *head, node **start) { node *p1 = head; node *p2 = head; if(NULL == head || NULL == head->next) { //head为NULL 或 链表为空返回false return false; } do { p1 = p1->next; //p1走一步 p2 = p2->next->next; //p2走两步 }while(p2 && p2->next && p1 != p2); if(p1 == p2) { *start = p1; //p1为回环开始节点 return true; } else { return false; } }
void print(node *head) { int pos = 0; node *p = head; while(NULL != p) { printf("the %dth node %d\n", ++pos, p->data); p = p->next; } } int main() { bool bLoop = false; node *head = InsertSort(); //创建并正向排序链表 printf("Link Sort...\n"); print(head); printf("IsLoop test.........\n"); node *start = head->next->next->next; //使第四个节点为回环开始位置 start->next = head->next; //回环连接到第二个节点 node *loopStart = NULL; bLoop = IsLoop(head, &loopStart); printf("bLoop = %d\n", bLoop); printf("bLoop == loopStart ? %d\n", (loopStart == start)); return 0; }
please input the data: 1 please input the data: 6 please input the data: 4 please input the data: 5 please input the data: 3 please input the data: 2 please input the data: 0 Link Sort... the 1th node 1 the 2th node 2 the 3th node 3 the 4th node 4 the 5th node 5 the 6th node 6 IsLoop test......... bLoop = 1 bLoop == loopStart ? 1 Press any key to continue