/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
}
};
1.借鉴大佬思路,首先建立vector,然后把节点对应的值push进去,排序,然后构建新链表,依次键入
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
//设置vector
vector<int> vec;
ListNode* cur=head;
//cur=ListNode* head;自己写的,应该是上一句
while(cur){
vec.push_back(cur->val);
cur=cur->next;
}
//vec.sort(vec.begin(),vec.end());
sort(vec.begin(),vec.end());
//构建新链表
ListNode* Dummy=new ListNode(0);
ListNode* Res=new ListNode(0);
Dummy->next=Res;
for(int i:vec){
Res->next=new ListNode(i);
Res=Res->next;
}
Res->next=nullptr;
returm Dummy->next->next;
}
};
2.去找了一个类似的题,按照大佬的思路,第一次写对了!!!!!!!开心
其实思路跟上面是一样的,只不过vector的排序函数sort(),变成了reverse函数
https://www.w3cschool.cn/cpp/cpp-i6da2pq0.html
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
vector<int> vec;
ListNode* cur=pHead;
while(cur)
{
vec.push_back(cur->val);
cur=cur->next;
}
reverse(vec.begin(), vec.end());
ListNode* dummy=new ListNode(0);
ListNode* res=new ListNode(0);
dummy->next=res;
for(int i:vec)
{
res->next=new ListNode(i);
res=res->next;
}
res->next=nullptr;
return dummy->next->next;
}
};