链表相关考题

1.判断一个链表是否为回文结构:

  方法1:T=O(n),S=O(n), 利用栈把链表每个元素入栈,然后依次出栈和链表元素对比。

  方法2:T=O(n/2),S=O(n),设置两个指针,一个快指针(一次前进两步),一个慢指针,目的是找到链表的中间的位置。

      分析:当链表元素个数为奇数时,快指针.next=null时(一定会走到.next=null),则此时移动后的慢指针就是中间位置。

         当偶数时,快指针=null时(必然会走到null),移动前的慢指针就是中间两个元素的左边位置。

        当得到中间位置的指针时,只需将一半的链表入栈,进行对比。

  方法3:T=O(n),S=O(1),将后半部分指针翻转,如 1->2->3->2->1 变换成1->2->3<-2<-1

      从两边一起往中间走,逐个判断,当左指针和右指针相同(奇数个)或左在右右边,(偶数个)时,判断停止public static boolean isPalindrome(ListNode pHead) {

// write code here
        ListNode slow=pHead;
        ListNode fast=pHead;
        while(fast!=null&&fast.next!=null) {
            fast=fast.next.next;
            slow=slow.next;
        }
        
        ListNode right;
     //从slow开始翻转(如果是偶数,如1,2,3,3,2,1,奇数时如1,2,3,2,1 右半部分都是1,2,3
     //无论是奇是偶,只需把右半部分比较完即可 right
=reverse(slow); ListNode current=pHead;
while(right!=null) { if(current.val!=right.val) return false; current=current.next; right=right.next; } return true; }

//翻转右半部分
public static ListNode reverse(ListNode head) { ListNode n1=head; ListNode current=head.next; n1.next=null; ListNode n2=current; while(current!=null) { n2=current; ListNode tmp=current.next; n2.next=n1; n1=current; current=tmp; } return n2; }

猜你喜欢

转载自www.cnblogs.com/lshao/p/9032252.html