浅析Sort List和判断回文List中链表中间节点的确定方法
1.在使用merge方法对链表排序,以及判断List是否是回文的时候,我们都需要确定中间节点,并从中间节点将链表断开
然后对于sortList ,将前后链表进行merge
对于回文list,将后一段链表翻转,并和前一段链表进行逐个比较
具体代码如下
Palindrome Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverse(ListNode head){
if(head==null) return null;
if(head.next==null){return head;}
ListNode ruNode=head;
ListNode preNode=null;
ListNode result=null;
while(ruNode!=null){
ListNode temp=ruNode.next;
if(temp==null){
result=ruNode;//the last node is the node of result list
}
ruNode.next=preNode;
preNode=ruNode;
ruNode=temp;//next loop
}
return result;
}
public boolean isPalindrome(ListNode head) {
if(head==null) return true;
if(head.next==null) return true;
ListNode slow = head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode temp=slow;
ListNode l2=null;
if(fast==null){
l2=reverse(temp);
}
else{
l2=reverse(temp.next);
}
slow.next=null;
while(l2!=null){
if(l2.val!=head.val){
return false;
}
head=head.next;
l2=l2.next;
}
return true;
}
}
在这里面
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode temp=slow;
ListNode l2=null;
if(fast==null){
l2=reverse(temp);
}
else{
l2=reverse(temp.next);
}
slow.next=null;
对于1->2->3->4
在while循环后,slow=3,fast=null。此时后半段应该是3->4
对于1->2->3->4->5
在while循环后,slow=3,fast=5。此时后半段应该是4->5
SortList
代码如下:
public class Solution {
public ListNode merge(ListNode l1,ListNode l2){
ListNode dummyNode=new ListNode(0);
ListNode ruNode=dummyNode;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
ruNode.next=l1;
l1=l1.next;
ruNode=ruNode.next;
}
else{
ruNode.next=l2;
l2=l2.next;
ruNode=ruNode.next;
}
}
if(l1!=null){
ruNode.next=l1;
}
if(l2!=null){
ruNode.next=l2;
}
return dummyNode.next;
}
public ListNode sortList(ListNode head) {
//mergesort
if(head==null) return null;
if(head.next==null) return head;
ListNode slow=head;
ListNode fast=head;
ListNode pre=null;//维持这个很重要
while(fast!=null&&fast.next!=null){
pre=slow;
slow=slow.next;
fast=fast.next.next;
}
对于1->2->3->4
在while循环后,slow=3,fast=null。此时后半段应该是3->4
对于1->2->3->4->5
在while循环后,slow=3,fast=5。此时后半段应该是3->4->5
pre.next=null;
ListNode l2=slow;(注意这一点,slow永远是中间那个)
ListNode l1=head;
ListNode result1=sortList(l1);
ListNode result2=sortList(l2);
return merge(result1,result2);
}
}