感觉是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;
return digui(lists,0,lists.length-1);
}
public ListNode digui(ListNode[] lists,int i,int j){
if(i==j)return lists[i];
int num=i+(j-i)/2;
ListNode left=digui(lists,i,num);
ListNode right=digui(lists,num+1,j);
return hecheng(left,right);
}
public ListNode hecheng(ListNode list1,ListNode list2){
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
if(list1.val<list2.val){
list1.next=hecheng(list1.next,list2);
return list1;
}else{
list2.next=hecheng(list1,list2.next);
return list2;
}
}
}
递归成两个有序链表,然后再进行两个链表合成,两个有序链表递归合成同样十分精彩;
快慢指针法
/**
* 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 middleNode(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode p1=head;
ListNode p2=head;
while(p2!=null&&p2.next!=null){
p1=p1.next;
p2=p2.next.next;
}
return p1;
}
}
这题可以有三种解法
前半反转、后半反转、和全反转
前两个都是使用快慢指针法、与上方法类似,后半部分反转即可,代码较简单
龟兔赛跑
当乌龟追上兔子时,兔子比乌龟多跑了n圈,而乌龟跑了n圈,还差a步到环入口,所有乌龟从头开始跑,直到第二次相遇,则相遇必为环的入口;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode h=head;
ListNode t=head;
while(t!=null&&t.next!=null){
h=h.next;
t=t.next.next;
if(h==t){
return true;
}
}
return false;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode p1=head;
ListNode p2=head;
while(p2!=null&&p2.next!=null){
p1=p1.next;
p2=p2.next.next;
if(p1==p2){
p1=head;
while(true){
if(p1==p2){//注意这点在后,首尾相同是第三次相遇
return p1;
}
p1=p1.next;
p2=p2.next;
}
}
}
return null;
}
}