采用快慢针的方法,ListNode p指向链表头部,ListNode q = p.next。再定义一个ListNode start表示删除指定val值后的头结点,先赋值为p。结点的遍历从q结点开始,当q.val不等于val时,p的下一个结点指向q,并且p、q同时向后移动,直至q=null,表示遍历链表结束,此时p.next = null。因为一开始我们是从第二个结点开始遍历链表的,所以最后我们要对start结点进行判断start.val是否和val相等,如果相等那么返回start.next,否则返回start
public class RemoveElements { public static void main(String[] args) { ListNode one = new ListNode(1); ListNode two = new ListNode(1);// ListNode three = new ListNode(6);// ListNode four = new ListNode(3);// ListNode five = new ListNode(4);// ListNode six = new ListNode(5);// ListNode seven = new ListNode(6); one.next = two; two.next = null;// three.next = four;// four.next = five;// five.next = six;// six.next = seven;// seven.next = null; ListNode listNode = removeElements(one, 1); printLink(listNode); } public static void printLink(ListNode head) { if (null == head) System.out.println("head is null"); while (head != null) { System.out.println(head.val); head = head.next; } } public static ListNode removeElements(ListNode head, int val) { if (null == head) return head; ListNode p = head, q = p.next, start = p; while (q != null) { if (q.val != val) { p.next = q; p = p.next; } q = q.next; } p.next = null; if (start.val == val) return start.next; return start; }}复制代码