考試結束,班級平均分只拿到了年級第二,班主任因而問道:你們都知道世界第一高峯珠穆朗瑪峯,有人知道世界第二高峯是什麼嗎?正當班主任要繼續發話,只聽到角落默默想起來一個聲音:」喬戈裏峯」java
2018.11.6號打卡程序員
明天的題目:https://leetcode-cn.com/problems/remove-linked-list-elements/
之後明天的題目提取公佈一下哈,由於有些朋友想提早作一下~面試
leetcode234-迴文鏈表
中文連接:
https://leetcode-cn.com/problems/palindrome-linked-list/
英文鏈表:
https://leetcode.com/problems/palindrome-linked-list/
難度:easy
分類:鏈表編程
請判斷一個鏈表是否爲迴文鏈表。測試
示例 1:spa
輸入: 1->2
輸出: false
示例 2:code
輸入: 1->2->2->1
輸出: trueblog
距離AC只差一個測試用例的錯誤思路element
代碼leetcode
1/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9class Solution { 10 public boolean isPalindrome(ListNode head) { 11 int sum1 = 0; 12 if(head == null || head.next == null) 13 return true; 14 int count = 1; 15 ListNode temp = head; 16 while(temp != null) 17 { 18 sum1 += count * temp.val; 19 count += 1; 20 temp = temp.next; 21 } 22 int sum2 = 0; 23 count = 1; 24 head = reverseList(head); 25 temp = head; 26 while(temp != null) 27 { 28 sum2 += count * temp.val; 29 count += 1; 30 temp = temp.next; 31 } 32 if(sum1 == sum2) 33 return true; 34 return false; 35 } 36 public ListNode reverseList(ListNode head) { 37 if(head == null || head.next == null) 38 return head; 39 ListNode pre = head; 40 ListNode pNode = head.next; 41 ListNode next = head; 42 //首先處理前兩個節點; 43 pre.next = null; 44 while(pNode != null) 45 { 46 next = pNode.next; 47 pNode.next = pre; 48 pre = pNode; 49 pNode = next; 50 } 51 return pre; 52 } 53}
結果,差一個用例沒過,說明這種方法仍是有點問題~~~~
dasda
正確的思路
代碼
1/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9class Solution { 10 public boolean isPalindrome(ListNode head) { 11 if(head == null || head.next == null) 12 return true; 13 int length = 0; 14 ListNode temp = head; 15 while(temp != null) 16 { 17 length++; 18 temp = temp.next; 19 } 20 int halfLength = length / 2; 21 temp = head; 22 for(int i=0;i<halfLength;i++) 23 temp = temp.next; 24 ListNode pre = temp; 25 ListNode pNode = temp.next; 26 ListNode next = pNode; 27 while(pNode != null) 28 { 29 next = pNode.next; 30 pNode.next = pre; 31 pre = pNode; 32 pNode = next; 33 } 34 for(int i=0;i<halfLength;i++) 35 { 36 if(head.val != pre.val) 37 return false; 38 head = head.next; 39 pre = pre.next; 40 } 41 return true; 42 } 43}
代碼講解
2018.11.6號 打卡
做者喬戈裏親歷2019秋招,哈工大計算機本碩,百度准入職java工程師,歡迎你們關注個人WX公衆號:程序員喬戈裏,公衆號有3T編程資源,以及我和我朋友(准入職百度C++工程師)在秋招期間整理的近200M的面試必考的java與C++面經,並有天天一道leetcode打卡羣與技術交流WX羣,歡迎關注。