Palindrome Linked List

本文介绍了一种用于判断单链表是否为回文的有效算法。该算法通过反转链表的后半部分并与前半部分进行比较来实现,能够在O(n)时间内完成,并且仅使用O(1)额外空间。

1. Title

Palindrome Linked List

2. Http address

https://leetcode.com/problems/palindrome-linked-list/

3. The question

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

4. My code(AC)

 1         public ListNode getKthNode(ListNode head, int k)
 2     {
 3         
 4         int re = 1;
 5         ListNode p = head;
 6         while( re <= k && p != null)
 7         {
 8             if( re == k)
 9             {
10                 return p;
11             }
12             re++;
13             p = p.next;
14         }
15         return null;
16     }
17     public int getLength(ListNode head)
18     {
19         int re = 0;
20         ListNode p = head;
21         while( p != null)
22         {
23             re++;
24             p = p.next;
25         }
26         return re;
27     }
28     
29         
30     public ListNode revLinked(ListNode head)
31     {
32         ListNode dump = new ListNode(0);
33         ListNode p = head;
34         ListNode tmp = null;
35         while( p != null)
36         {
37             tmp = p.next;
38             p.next = dump.next;
39             dump.next = p;
40             p = tmp;
41         }
42         return dump.next;
43     }
44     
45     
46     public boolean isPalindrome(ListNode head) {
47         
48         if( head == null || head.next == null)
49             return true;
50         
51         int len = getLength(head);
52         ListNode p,q;
53         q = getKthNode(head, (len / 2) + 1);
54         q = revLinked(q);
55         p = head;
56         while( q != null && p != null)
57         {
58             if( q.val != p.val)
59             {
60                 return false;
61             }
62             p = p.next;
63             q = q.next;
64         }
65        return true;        
66     }

 

转载于:https://www.cnblogs.com/ordili/p/4928513.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值