採用快慢針的方法,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;
}
}複製程式碼