博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
234. Palindrome Linked List
阅读量:4942 次
发布时间:2019-06-11

本文共 1693 字,大约阅读时间需要 5 分钟。

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?

 

public bool IsPalindrome(ListNode head) {if(head == null) return true;// Reverse the head;ListNode standForward  = new ListNode(0);ListNode stand  =standForward;ListNode newHead = null;while(head != null)    {        standForward.next = new ListNode(head.val);        ListNode nextNode = head.next;        head.next = newHead;        newHead = head;        head = nextNode;                standForward = standForward.next;    }while(newHead != null){    if(stand.next.val != newHead.val) return false;    stand=stand.next ;    newHead = newHead.next;}return true;}

 

 

if use space O(1), we need to use 2 pointer to find the middle pointer of linked list and then reverse the second part of the linked list.

public bool IsPalindrome(ListNode head) {         if(head == null) return true;         ListNode slow = head;         ListNode fast = head;         ListNode nextNode = null;         ListNode newHead = null;                  //get middle pointer of the linked list         while(fast != null && fast.next != null)         {             slow = slow.next;             fast = fast.next.next;         }                   while(slow != null)             {                 nextNode = slow.next;                 slow.next = newHead;                 newHead = slow;                 slow = nextNode;             }         while(head != null && newHead != null)         {             if(head.val != newHead.val) return false;             head = head.next;             newHead = newHead.next;         }         return true;     }

 

转载于:https://www.cnblogs.com/renyualbert/p/5854771.html

你可能感兴趣的文章
分布式存储系统可靠性如何估算?
查看>>
吴恩达深度学习笔记 course 2 1.1~1.14 深度学习的实用层面
查看>>
统计学习方法十:隐马尔科夫模型
查看>>
jq监听页面的滚动事件,
查看>>
Swift - Realm数据库的使用详解(附样例)
查看>>
Linux服务器开发初步
查看>>
Android Fragment 你应该知道的一切
查看>>
Application
查看>>
【BZOJ】【1045/1465】【HAOI2008】糖果传递
查看>>
Android 之窗口小部件详解--App Widget
查看>>
Android之Toolbar的三个问题:修改左边箭头颜色、怎样修改右边以及子activity中的toolbar添加返回箭头...
查看>>
Android开发之StrictMode
查看>>
熟悉JSON
查看>>
Scrum立会报告+燃尽图(Beta阶段第一次)
查看>>
Scrum立会报告+燃尽图(Final阶段第二次)
查看>>
INSTR
查看>>
8 传输层----TCP
查看>>
Android - 应用程序的优先级和进程状态
查看>>
源码学习-String类
查看>>
Kafka创建&查看topic,生产&消费指定topic消息
查看>>