1. 题目链接:合并两个链表力扣https://leetcode.cn/problems/merge-two-sorted-lists/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* head = new ListNode(-1);//哨兵
ListNode*tail = head;
tail->next=NULL;
while(list1&&list2)
{
if(list1->val<list2->val)
{
tail->next = list1;
tail = tail->next;
list1= list1->next;
}else{
tail->next = list2;
tail = tail->next;
list2= list2->next;
}
}
if(list1)
tail->next = list1;
if(list2)
{
tail->next = list2;
}
return head->next;
}
};
带哨兵:较为简单
不带哨兵 :较为复杂,就需要考虑头结点为空的情况
2.找倒数第K个节点:使用 快慢指针
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
struct ListNode* slow ,*fast;
fast = slow = pListHead;
while(k--)
{
if(fast==NULL)
return NULL;
fast = fast->next;
}
while(fast!=NULL)
{
slow = slow->next;
fast = fast ->next;
}
//快慢指针 : 先走k步,然后fast slow 同时走,当fast==NULL
return slow;
}
};
思路:
定义两个链表,四个节点指针 :头 尾
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* smallHead = new ListNode(-1);
ListNode* bigHead = new ListNode(-1);
ListNode* pstail =smallHead,*pbtail = bigHead,*cur = pHead;
while(cur)
{
if(cur->val < x)
{
pstail->next = cur;
pstail = pstail->next;//移到到新节点
}else{
pbtail->next = cur;
pbtail = pbtail->next;
}
cur = cur->next;
}
pbtail->next=NULL;
pstail->next = bigHead->next;
return smallHead->next;
}
};