classSolution{ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode dummy = new ListNode(0); dummy.next = head; ListNode first = dummy, second = dummy; for (int i = 1; i <= n+1; i++) first = first.next; while(first != null){ first = first.next; second = second.next; } second.next = second.next.next; return dummy.next; } }
Posted onInLeetcode
,
Linked List Symbols count in article: 693Reading time ≈1 mins.
Question
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Posted onInLeetcode
,
Linked List Symbols count in article: 818Reading time ≈1 mins.
Question
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note thatposis not passed as a parameter.
Posted onInLeetcode
,
Linked List Symbols count in article: 718Reading time ≈1 mins.
Question
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return trueif there is a cycle in the linked list. Otherwise, return false.
classSolution{ //pq,time O(nlogk), space O(K) public ListNode mergeKLists(ListNode[] lists){ if (lists.length == 0) returnnull; ListNode dummy = new ListNode(0); PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val); for (int i = 0; i < lists.length; i++) if (lists[i] != null) pq.offer(lists[i]);//only first element will be insert to the pq ListNode cur = dummy; while(!pq.isEmpty()){ cur.next = pq.poll(); cur = cur.next; if (pq.isEmpty()) break; //last cycle dont need work if (cur.next != null) pq.offer(cur.next); } return dummy.next; } }