LeetCode-Sort a linked list using insertion sort(链表插入排序)

版权声明: https://blog.csdn.net/github_37209555/article/details/79910982

链表插入排序包含两种技术,一个是链表操作,另一个是插入排序思想

这道题我整体的思路是正确的,但是搞了差不多三个小时的时间才AC,期间踩了很多坑,一些是自己挖的,一些是由于基础知识不牢固导致。

题目:Sort a linked list using insertion sort

给定结构体:这是一个单链表结构体

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };

其中值、指向下一个节点的指针、还有一个构造函数。

插入排序思想:

    将待排序元素依次插入排序好的序列中,时间复杂度是n²

单链表特点:

    无法随机访问,方便插入,无需移动数据(相比于数组),并且当你想要插入移动指针前面的位置的时候有点困难

在这次练习中我还发现链表的调试比较困难,有一些没有想到的问题出现。


题目思想:

    拿到这道题,觉得很简单,无非就是搞两个链表,两个循环,一个指针在给定的链表中走,一个指针在输出链表中走

遍历输出链表,插入合适位置。这个思路没什么问题,这道题的难点也不在思路上,我认为在链表的操作上面有很多细节问题需要注意。

出现的问题:

在VS上可以编译运行,但是在给定的环境里无法运行,报double free()错误,结果发现是结构体初始化时候的错误

ListNode *sortedlist=new ListNode(0);
//sortedlist = &n;

上面是正确的初始化方式,下面的方式会有问题,但目前不知道具体的问题所在!

下面是全部代码,感觉很啰嗦,有时间改进!

/**
 * 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)
        {return head;}
		//ListNode n(9);
		ListNode *sortedlist=new ListNode(0);
        //sortedlist = &n;
		ListNode *h = sortedlist;
		ListNode *w = head;
		if (head != NULL) {
			sortedlist->val = head->val;
			sortedlist->next = NULL;
			head = head->next;
			h = sortedlist;
			w=sortedlist;
		}
	    while (head != NULL) {
			while (h != NULL && head!= NULL) {
				if (head->val >= h->val) {
					if (h->next != NULL) {
						if (head->val <= h->next->val) {
							w = head;
							head = head->next;
							w->next = h->next;
							h->next = w;
							h = sortedlist;
							continue;
						}
					}
                    else {
                        w = head;
                        head = head->next;
                        w->next = NULL;
                        h->next = w;
                        h = sortedlist;
                        continue;
                    }
				}
				else if (head->val < h->val) {
					w = head;
					head = head->next;
					w->next = h;
					h = w;
					sortedlist = w;
					continue;
				}
				h = h->next;
				//ListNode n(h->val);
			}
			if(head != NULL){ head = head->next; }
			
		}
		return sortedlist;
        //return head;
    }
};

猜你喜欢

转载自blog.csdn.net/github_37209555/article/details/79910982