Leetcode 147. Insertion Sort List
来源:互联网 发布:淘宝购物高峰期 编辑:程序博客网 时间:2024/06/06 12:56
题目:
Sort a linked list using insertion sort.
思路:
使用一个指针p指向未排好序的链表的第一个结点,在排序好的部分中找到找第一个大于等于q的前驱结点,将p对应的结点插入到正确位置,p重新指向未排好序的链表的第一个结点。直到链表完成排序好。
代码实现
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *insertionSortList(ListNode *head){ if (head == NULL || head->next == NULL) return head; ListNode *p = head->next; head->next = NULL; while (p != NULL) { ListNode *pNext = p->next; /*store the next node to be insert*/ ListNode *q = head; if (p->val < q->val) /*node p should be the new head*/ { p->next = q; head = p; } else { while (q != NULL && q->next != NULL && q->next->val <= p->val) q = q->next; p->next = q->next; q->next = p; } p = pNext; } return head;}};
阅读全文
0 0
- LeetCode 147. Insertion Sort List
- [LeetCode]147.Insertion Sort List
- [leetcode] 147.Insertion Sort List
- 147. Insertion Sort List LeetCode
- LeetCode 147. Insertion Sort List
- LeetCode *** 147. Insertion Sort List
- Leetcode 147. Insertion Sort List
- leetcode.147. Insertion Sort List
- leetcode 147. Insertion Sort List
- LeetCode-147.Insertion Sort List
- LeetCode - 147. Insertion Sort List
- [leetcode] 147. Insertion Sort List
- [LeetCode] 147. Insertion Sort List
- Leetcode-147. Insertion Sort List
- [LeetCode]147. Insertion Sort List
- LeetCode 147. Insertion Sort List
- 【LeetCode】 147. Insertion Sort List
- Leetcode 147. Insertion Sort List
- hack this site--level 3
- haproxy停掉后,keepalived主备没有切换
- 笔记四 小球滚动
- SE01 Unit01 API文档 、 字符串基本操作
- Shell脚本——su、sudo
- Leetcode 147. Insertion Sort List
- putty提示Network error:Software caused connection abort解决方法
- Django settings.py配置文件
- android gradle tools 3.X 中依赖,implement、api 指令
- ssh-port-redirect-in-linux-system
- 解决sql查询时间缺失
- centos 如何关闭防火墙?
- 函数
- js中数组的基本操作