提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- [一、21. 合并两个有序链表](#一、21. 合并两个有序链表)
- [二、力扣86. 分隔链表](#二、力扣86. 分隔链表)
- [三、力扣23. 合并 K 个升序链表](#三、力扣23. 合并 K 个升序链表)
- [四、力扣删除链表的倒数第 N 个结点](#四、力扣删除链表的倒数第 N 个结点)
前言
一、21. 合并两个有序链表
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode res = new ListNode(), pre = res;
ListNode p1 = list1, p2 = list2;
while(p1 != null && p2 != null){
if(p1.val <= p2.val){
pre.next = p1;
p1 = p1.next;
pre = pre.next;
}else{
pre.next = p2;
p2 = p2.next;
pre = pre.next;
}
}
while(p1 != null){
pre.next = p1;
p1 = p1.next;
pre = pre.next;
}
while(p2 != null){
pre.next = p2;
p2 = p2.next;
pre = pre.next;
}
return res.next;
}
}
二、力扣86. 分隔链表
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dump1 = new ListNode(-1,null);
ListNode dump2 = new ListNode(-1,null);
ListNode p = head, p1 = dump1, p2 = dump2;
while(p != null){
if(p.val < x){
p1.next = p;
p1 = p1.next;
}else{
p2.next = p;
p2 = p2.next;
}
ListNode temp = p.next;
p.next = null;
p = temp;
}
p1.next = dump2.next;
return dump1.next;
}
}
三、力扣23. 合并 K 个升序链表
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0){
return null;
}
ListNode res = new ListNode(-1,null);
ListNode r = res;
PriorityQueue<ListNode> pq = new PriorityQueue<>(
lists.length, (a,b)->(a.val - b.val)
);
for(ListNode node : lists){
if(node != null){
pq.add(node);
}
}
while(!pq.isEmpty()){
ListNode p = pq.poll();
r.next = p;
if(p.next != null){
pq.add(p.next);
}
r = r.next;
}
return res.next;
}
}
四、力扣删除链表的倒数第 N 个结点
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p1 = head;
for(int i = 0; i < n; i ++){
p1 = p1.next;
}
if(p1 == null){
return head.next;
}
ListNode p2 = head;
while(p1.next != null){
p1 = p1.next;
p2 = p2.next;
}
p2.next = p2.next.next;
return head;
}
}