面试题—数据结构之单链表详述(基本篇3)

来源:互联网 发布:淘宝评价后怎么截图 编辑:程序博客网 时间:2024/06/16 18:40

           单链表的正向排序,就是插入数据时就按从小到大排序。

代码有注释很容易理解的:

//单链表的正向排序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;}

判断单链表是否存在环型链表问题,这里有一种比较简单的解法,假设两个指针分别为p1和p2,每循环一次p1向前走一步,p2向前走两步,直到p2碰到NULL指针或者两个指针相等时循环结束。如果两个指针相等则说明存在环。

程序代码如下:

//判断单链表是否存在回路//如果存在,start存放回环开始的节点bool IsLoop(node *head, node **start){node *p1 = head;node *p2 = head;if(NULL == head || NULL == head->next){//head为NULL 或 链表为空返回falsereturn 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;}

下面是程序执行结果:输入是1 6 4 5 3 2

please input the data: 1please input the data: 6please input the data: 4please input the data: 5please input the data: 3please input the data: 2please input the data: 0Link Sort...the 1th node 1the 2th node 2the 3th node 3the 4th node 4the 5th node 5the 6th node 6IsLoop test.........bLoop = 1bLoop == loopStart ? 1Press any key to continue


原创粉丝点击