1. 题目链接:合并两个链表力扣https://leetcode.cn/problems/merge-two-sorted-lists/
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->valval)
{
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个节点:使用 快慢指针
链表中倒数第k个结点_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&&tqId=11167&rp=2&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking
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;
}
};
3.分割:链表分割_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId=8&&tqId=11004&rp=2&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking
思路:
定义两个链表,四个节点指针 :头 尾
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;
}
};


