首页 > 代码库 > LeetCode 234. Palindrome Linked List
LeetCode 234. Palindrome Linked List
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?
Solution 1 (loop through and use two-pointer O(n) time and O(n) space)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public int val; 5 * public ListNode next; 6 * public ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public bool IsPalindrome(ListNode head) { 11 if(head==null||head.next ==null) 12 { 13 return true; 14 } 15 List<int> list = new List<int>(); 16 ListNode node = head; 17 while(node!=null) 18 { 19 list.Add(node.val); 20 node=node.next; 21 } 22 int l = list.Count(); 23 int p1=0; int p2=l-1; 24 while(p1<=p2) 25 { 26 if(list[p1]==list[p2]) 27 { 28 p1++; 29 p2--; 30 } 31 else 32 { 33 return false; 34 } 35 } 36 return true; 37 38 39 } 40 }
Follow up/ Solution 2
Find the Middle node (two-pointer one fast one slow)
Then reverse the middle.next
Compare reversed to head until reversed==null
1 public class Solution { 2 public bool IsPalindrome(ListNode head) { 3 if(head==null||head.next ==null) 4 { 5 return true; 6 } 7 //Find the lower part from the list started from the middle.mext; 8 ListNode lower = FindMiddleNode(head).next; 9 //reverse lower to compare with the upper part 10 ListNode reversedLower = Reverse(lower); 11 while(reversedLower!=null) 12 { 13 if(reversedLower.val == head.val) 14 { 15 reversedLower = reversedLower.next; 16 head = head.next; 17 } 18 else 19 { 20 return false; 21 } 22 } 23 return true; 24 } 25 26 private ListNode FindMiddleNode(ListNode head) 27 { 28 ListNode slow = head; 29 //one step faster so middle for even is n/2 30 ListNode fast = head.next; 31 while(fast!=null && fast.next!=null) 32 { 33 slow = slow.next; 34 fast = fast.next.next; 35 } 36 return slow; 37 } 38 private ListNode Reverse(ListNode list) 39 { 40 if(list==null ||list.next == null) 41 { 42 return list; 43 } 44 ListNode prev = null; 45 while(list!=null) 46 { 47 ListNode temp = list.next; 48 list.next = prev; 49 prev= list; 50 list = temp; 51 } 52 return prev; 53 } 54 }
LeetCode 234. Palindrome Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。