这几道题都是典型的listnode节点类型问题
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)return l2;
if(l2==null)return l1;
ListNode a=l1;
ListNode b=l2;
ListNode head=null;
if(l1.val<l2.val){
head=l1;
a=a.next;
}else{
head=l2;
b=b.next;
}
ListNode p=head;
while(a!=null&&b!=null){
if(a.val>b.val){
p.next=b;
p=p.next;
b=b.next;
}else{
p.next=a;
p=p.next;
a=a.next;
}
}
if(a==null&&b==null){
return head;
}else if(a==null&&b!=null){
p.next=b;
}else{
p.next=a;
}
return head;
}
}
23
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
if (lists.length == 1) return lists[0];
PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) queue.add(lists[i]);
}
ListNode dummy = new ListNode(-1), cur = dummy;
while (!queue.isEmpty()) {
ListNode temp = queue.poll();
cur.next = temp;
cur = temp;
if (temp.next != null) queue.add(temp.next);
}
return dummy.next;
}
}
24
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null)
return null;
//表头节点,默认链表中的数据都为正数
ListNode preHead = new ListNode(-1);
preHead.next=head;
ListNode left=preHead;
ListNode mid=head;
if(head.next==null)
return head;
ListNode right=head.next;
while(mid!=null && mid.next!=null){
mid.next=right.next;
right.next=mid;
left.next=right;
left=mid;
mid=left.next;
if(mid!=null)
right=mid.next;
}
return preHead.next;
}
}
25
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode root = new ListNode(-1);
root.next = head;
ListNode res = root;
ListNode temp = head;
int i = 0;
while(temp != null){
i++;
temp = temp.next;
}
while(i >= k){
for(int j = 0 ; j < k-1; j++){
ListNode node = root.next;
root.next = head.next;
head.next = root.next.next;
root.next.next = node;
}
root = head;
head = head.next;
i-=k;
}
return res.next;
}
}
节点问题真的是让我头疼很久,指针,节点移动不画图完全搞不懂
不过多做几次,还是挺容易看懂的。