1819202122232425
public static void main(String[] args) { int[] arr = {12, 11, 12, 21, 41, 43, 21}; LinkedList list = new LinkedList(arr); ListNode head = removeDups(list); head.print(); }
3132333435363738394041424344
// use a hash set to track pre-existed node Set<Integer> set = new HashSet<Integer>(); // use a fake head ListNode head = new ListNode(); ListNode prev = head; ListNode node = list.head; while (node != null) { if (!set.contains(node.val)) { prev.next = node; prev = node;
1415161718192021
public class Q032_Sort_a_linked_list_of_0s_1s_and_2s { public static void main(String[] args) { LinkedList list = new LinkedList(new int[]{0, 1, 0, 2, 1, 1, 2, 1, 2}); ListNode res = sortList(list.head); res.print(); }
24252627282930313233343536373839404142434445
if (head == null) { return null; } // list of 0s ListNode f0 = new ListNode(); ListNode p0 = f0; // list of 1s ListNode f1 = new ListNode(); ListNode p1 = f1; // list of 2s ListNode f2 = new ListNode(); ListNode p2 = f2; ListNode p = head; while (p != null) { switch (p.val) { case 0: p0.next = p; p0 = p;
2829303132333435363738
if (head == null) { return null; } int count = 1; ListNode p = head; while (p != null && count < n) { p = p.next; count++; }
4344454647484950515253
public static void main(String[] args) { // Initialize a linked list LinkedList list = new LinkedList(10); ListNode node = getNth(list.head, 5); if (node != null) { System.out.println(node.val); } else { System.out.println("No such node");
public static void main(String[] args) { int[] arr = {11, 11, 11, 21, 43, 43, 60}; LinkedList list = new LinkedList(arr); ListNode head = removeDups(list); head.print(); }
282930313233343536373839404142
if (list == null || list.head == null) { return null; } // use a fake head ListNode head = new ListNode(); ListNode prev = head; ListNode slow = list.head; ListNode fast = null; while (slow != null) { // count the occurrances of slow int count = 1; fast = slow.next;
2526272829303132333435
static void deleteAlternate(LinkedList list) { if (list == null) { return; } ListNode node = list.head; while (node != null && node.next != null) { node.next = node.next.next; node = node.next; }
4041424344454647484950
// step 1. reverse the linked list head = reverse(head); head.print(); // step 2. go through list, if next node is smaller than current max, delete it ListNode current = head; int max = current.val; while (current != null && current.next != null) { // 1. 注意:循环条件 if (current.next.val >= max) { // update max