目录
1. 反转链表19
if(head==null || head.next==null) return head;
ListNode now =head;
ListNode next = head.next;
ListNode n =null;
while(next!=null){
now.next=n;
n=now;
now=next;
next=next.next;
}
now.next=n;
return now;
2. 翻转指定区间29
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode pre=dummy,p=head;
int index=1;
while(index!=m){
pre=pre.next;
p=p.next;
index++;
}
ListNode tail=p;
while(index<=n){
ListNode temp=p;
p=p.next;
temp.next=pre.next;
pre.next=temp;
index++;
}
tail.next=p;
return dummy.next;
}
3.k个一组翻转40
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
int size=0;
ListNode p=head;
while(p!=null){
size++;
p=p.next;
}
if(size<k) return head;
int index =1;
ListNode n=null;
p=head;
ListNode temp =p;
while(index<=k){
temp=p;
p=p.next;
temp.next=n;
n=temp;
index++;
}
head.next=reverseKGroup(p,k);
return temp;
}
4.合并有序链表47
public ListNode Merge (ListNode pHead1, ListNode pHead2) {
// write code here
ListNode res=new ListNode(-1),p=res;
ListNode p1=pHead1,p2=pHead2;
while(p1!=null && p2!=null){
if(p1.val<=p2.val){
p.next=p1;
p1=p1.next;
}else{
p.next=p2;
p2=p2.next;
}
p=p.next;
}
if(p1==null){
p.next=p2;
}
if(p2==null){
p.next=p1;
}
return res.next;
}
5.合并k个有序00
public ListNode mergeKLists (ArrayList<ListNode> lists) {
// write code here
if(lists.size()==0) return null;
PriorityQueue<ListNode> q=new PriorityQueue<>(lists.size(),(ListNode a,ListNode b)->a.val-b.val);
ListNode res=new ListNode(-1);
for(ListNode p:lists){
if(p!=null)
q.offer(p);
}
ListNode p=res;
while(!q.isEmpty()){
ListNode temp=q.poll();
if(temp.next!=null){
q.offer(temp.next);
}