LinkedList Easy 1.83.Remove Duplicates from Sorted List 当前节点值如果和下一个节点值相同直接略过。 1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if ( head == null ) 4 return null ; 5 ListNode
LinkedList Easy
1. 83. Remove Duplicates from Sorted List
当前节点值如果和下一个节点值相同直接略过。
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if( head == null) 4 return null; 5 ListNode node = head; 6 while( node.next != null){ 7 if(node.next.val == node.val){ 8 node.next = node.next.next; 9 } 10 else 11 node = node.next; 12 } 13 return head; 14 } 15 }
2. 141. Linked List Cycle
用快慢针,如果有循环快慢针会在某一时刻相同
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if( head == null || head.next == null) 4 return false; 5 ListNode fast = head; 6 ListNode slow = head; 7 while( fast != null && fast.next != null){ 8 slow = slow.next; 9 fast = fast.next.next; 10 if( slow == fast) 11 return true; 12 } 13 return false; 14 } 15 }
3. 234. Palindrome Linked List
用快慢针找到链表重点,我们可以在找到中点后,将后半段的链表翻转一下,这样我们就可以按照回文的顺序比较了。
1 class Solution { 2 public boolean isPalindrome(ListNode head) { 3 if( head == null || head.next == null) 4 return true; 5 ListNode fast = head; 6 ListNode slow = head; 7 while(fast.next !=null && fast.next.next !=null){ 8 slow = slow.next; 9 fast = fast.next.next; 10 } 11 ListNode pre = head, last = slow.next; 12 while( last.next != null){ 13 ListNode temp = last.next; 14 last.next = temp.next; 15 temp.next = slow.next; 16 slow.next = temp; 17 } 18 while(slow.next != null){ 19 slow = slow.next; 20 if(pre.val != slow.val) 21 return false; 22 pre = pre.next; 23 } 24 return true; 25 } 26 }