(234)-(Palindrome Linked List)-(对一个单链表构成的string进行反转)-(这里有一个问题,头插法我只能做到0(N)的空间复杂度,有么有可能用头插做到O(1)的空间复杂度)
(234)-(Palindrome Linked List)-(对一个单链表构成的string进行反转)-(这里有一个问题,头插法我只能做到0(N)的空间复杂度,有么有可能用头插做到O(1)的空间复杂度) //之前有做过一个题目,判断是否回文子串的, //用到了特殊技巧,先归一成偶数长度的, //这个题目好像并不需要这样做, //首先,判断奇偶数,决定第二个指针待的位置, //将前半部分进行头插的倒置, //然后两个指针同时走,判断等不等,就OK了。 public class Solution { public boolean isPalindrome(ListNode head) { if(head==null||head.next==null) { return true; } int head_len=0; ListNode temp=head; //出bug的地方是这里,更改成temp!=null //while(temp.next!=null) while(temp!=null) { head_len++; temp=temp.next; } //1 2 3 4 从3开始,下标为2 即4/2 //1 2 3 从3开始,下标为2 ,即3/2+1 int target_index=0; if(head_len%2==0) { target_index=head_len/2; } else { target_index=head_len/2+1; } ListNode sec_head=head; for(int i=0;i<target_index;i++) { sec_head=sec_head.next; //转移到下一步 } //现在开始对比head与sec_head,脑残。忘记倒置了。哭,这记性啊 //开始头插法,对sec_head ListNode final_ans=new ListNode(0); ListNode r_ans; while(sec_head!=null) { r_ans=final_ans.next; ListNode curr_temp=new ListNode(sec_head.val); final_ans.next=curr_temp; curr_temp.next=r_ans; sec_head=sec_head.next; } //重新为sec_head赋值 sec_head=final_ans.next; int flag=1; while(sec_head!=null) { if(head.val==sec_head.val) { head=head.next; sec_head=sec_head.next; } else { flag=0; break; } } if(flag==0) { return false; } else { return true; } } }