Algorithm_Linked List
来源:互联网 发布:杭州认知网络 编辑:程序博客网 时间:2024/06/04 17:48
Sort List Problem
For God’s sake, don’t try sorting a linked list during the interview
So it might be better to actually copy the values into an array and sort them there.
Tip:
Since a node may be inserted before head, we can create a new_head that points to head.
Insertion Sort List:
My version:
ListNode* insertionSortList(ListNode* head) { if(head == NULL) return head; ListNode* new_head = new ListNode(numeric_limits<int>::min()); new_head->next = head; ListNode* right = head->next; head->next = NULL; while(right){ ListNode* rnext = right->next; right->next = NULL; ListNode* p = new_head; while(p){ if(p->next != NULL && p->next->val > right->val && p->val <= right->val){ right->next = p->next; p->next = right; break; } if(p->next == NULL){ p->next = right; break; } p = p->next; } right = rnext; } head = new_head->next; delete(new_head); return head;}
Better version:
ListNode* insertionSortList(ListNode* head) { ListNode* new_head = new ListNode(0); new_head -> next = head; ListNode* pre = new_head; ListNode* cur = head; while (cur) { if (cur -> next && cur -> next -> val < cur -> val) { while (pre -> next && pre -> next -> val < cur -> next -> val) pre = pre -> next; /* Insert cur -> next after pre.*/ ListNode* temp = pre -> next; pre -> next = cur -> next; cur -> next = cur -> next -> next; pre -> next -> next = temp; /* Move pre back to new_head. */ pre = new_head; } else cur = cur -> next; } ListNode* res = new_head -> next; delete new_head; return res;}
0 0
- Algorithm_Linked List
- List
- list
- List
- LIST
- list
- list
- List
- list
- list
- List
- list
- LIST
- List
- List
- List
- list
- list
- 数据传输压缩,节约带宽
- JAVA 集合 List 分组的两种方法
- POJ题单
- netty 二进制简单通信
- arduino 资料
- Algorithm_Linked List
- ubuntu下opera浏览器安装Flash插件
- 数学之美系列
- POJ 3278 Catch That Cow (bfs)(两种方式)
- Android中Toast的用法简介
- PAT 1013 数素数 为什么一直是19分
- 使用Spinner实现下拉列表
- 计算机网络之GBN协议
- Mysqldump原理