public class DeleteMin<T> { @SuppressWarnings({ "unchecked", "rawtypes", "hiding" }) public static <T extends Comparable> void deleteMin(linkList<T> La) { if (La.isEmpty()) { System.out.println("链表为空表"); } Node<T> p,q; p = La.getHead(); q = La.getHead().next; while (q != null) { for (int i = 0; i < La.size(); i++) { if (p.data.compareTo(q.data) <= 0) { q = q.next; } p = q; } p.next = p.next.next; } } public static void main(String[] args) { int [] arr={12,23,35,49,56}; linkList<Integer> La = new linkList<Integer>(); for (int i = 0; i < arr.length; i++) La.add(arr[i], i + 1); System.out.println("单链表arr中数据元素为:"); La.nextOrder(); deleteMin(La); System.out.println("单链表arr中数据元素为:"); La.nextOrder(); //de.deleteMin(head); } }
带头节点的单链表中删除最小值结点
if语句报空指针异常
Exception in thread "main" java.lang.NullPointerException
@SuppressWarnings({ "unchecked", "rawtypes", "hiding" }) public static <T extends Comparable> void deleteMin(linkList<T> La) { if (La.isEmpty()) { System.out.println("链表为空表"); } Node<T> p,q,k,w; k = La.getHead(); w = La.getHead(); p = La.getHead().next; q = La.getHead().next.next; while (q != null) { for (int i = 0; i < La.size()-1; i++) { if (p.data.compareTo(q.data) <= 0) { w = w.next; q = q.next; } else { k = p; p = q; q = q.next; w = w.next; } } } if (k.next == p) { k.next = p.next; } else { w.next = p.next; } }
因为前面找到了最小值节点但是由于是单链表没有前驱所有很难搞。我用四个指针完成了,这是删除算法,各位大佬能不能帮我优化一下,
@SuppressWarnings({ "unchecked", "rawtypes", "hiding" }) public static <T extends Comparable> void deleteMin(linkList<T> La) { if (La.isEmpty()) { System.out.println("链表为空表"); } Node<T> p, q; p = La.getHead().next; T Min = p.data; while (p != null) { if (p.data.compareTo(Min) <= 0) { Min = p.data; } p = p.next; } p = La.getHead(); q = La.getHead().next; while (q != null) { if (q.data.compareTo(Min) == 0) { p.next = q.next; break; } else { p = q; q = q.next; } } }
p.next.next p.next这个操作是否为空
谢谢你