cocowy的编程之旅
示例:
- 对于一个链表排序,我们可以有多种方法,
(1)递归
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode res = null;
ListNode p = head;
while(p != null) {
ListNode next = p.next;
res = insert(res, p);
p = next;
}
return res;
}
private ListNode insert(ListNode head, ListNode node) {
if(head == null || head.val > node.val) {
node.next = head;
return node;
}
head.next = insert(head.next, node);
return head;
}
}
(2)此为第二种,链表不进行增断链表,而是进行指针值的变动
struct ListNode* insertionSortList(struct ListNode* head) {
if(!head)
return NULL;
struct ListNode * p,*q;
int temp;
for(p=head;p;p=p->next)
{
for(q=p->next;q;q=q->next)
{
if(p->val>q->val)
{
temp=p->val;
p->val=q->val;
q->val=temp;
}
}
}
return head;
}
(3)此为第三种,在前面加一个头结点进行断链增链操作(新的链表排序)
struct ListNode* insertionSortList(struct ListNode* head) {
if(!head)
return NULL;
struct ListNode *L,*p,q;
L=(struct ListNode)malloc(sizeof(struct ListNode));
L->next=head;
p=head->next;
head->next=NULL;
while(p)
{
struct ListNode *curr=p->next;
q=L;
while(q->next&&q->next->val<=p->val)
q=q->next;
p->next=q->next;
q->next=p;
p=curr;
}
return L->next;
}
(4)指针值不动,不增加新的链表。(用原链表进行排序)
struct ListNode* insertionSortList(struct ListNode* head){
if(head==NULL||head->next==NULL) return head;
struct ListNode* rear,*p,*temp,*q ; //rear指向尾结点,q指向倒数第二个结点
rear = head->next;
q=head;
while(rear)
{
//找到不是升序的结点进行插入
while(rear&&rear->val>=q->val)
{
q = q->next;
rear = rear->next;
}
if(rear==NULL) break;
temp = rear;
rear = rear->next;//更新结点
//该节点小于头结点(特殊结点,头插法)
if(temp->val<head->val)
{
temp->next = head;
head = temp;
}
else//在链表中搜寻合适的插入位置
{
p = head;
while(temp->val>p->next->val)
p = p->next;
temp->next = p->next;
p->next = temp;
}
q->next=rear;//始终为相邻结点比较
}
return head;
}
作者:cocowy
链接:https://leetcode-cn.com/problems/insertion-sort-list/solution/pai-xu-de-san-chong-si-lu-di-gui-zeng-duan-lian-bi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
作者:cocowy
链接:https://leetcode-cn.com/problems/insertion-sort-list/solution/pai-xu-de-san-chong-si-lu-di-gui-zeng-duan-lian-bi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。