前言
经过前期的基础训练以及部分实战练习,粗略掌握了各种题型的解题思路。现阶段开始专项练习.
相关操作
查找中心节点
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
反转链表
public ListNode reverseList(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode new_head=reverseList(head.next);
head.next.next=head;
head.next=null;
return new_head;
}
合并链表
public void mergeList(ListNode l1, ListNode l2) {
ListNode l1_tmp;
ListNode l2_tmp;
while(l1!=null&&l2!=null){
l1_tmp=l1.next;
l2_tmp=l2.next;
l1.next=l2;
l1=l1_tmp;
l2.next=l1;
l2=l2_tmp;
}
}
合并有序链表
public ListNode merge(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l1.val<l2.val){
l1.next=merge(l1.next,l2);
return l1;
}else{
l2.next=merge(l1,l2.next);
return l2;
}
}