emove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
实现:
public static ListNode removeElements(ListNode head, int val) {
ListNode temp = head;
ListNode pre = null;
while(null != temp) {
if (temp.val == val) {
if (null == pre) {
head = temp.next;
}else{
pre.next = temp.next;
}
}else {
pre = temp;
}
temp = temp.next;
}
return head;
}
测试一下:
int array[] = {1,2,6,3,4,5,6}; ListNode head = ListNode.buildeListNode(array); ListNode.printListNode(head); ListNode.printListNode(removeElements(head,6));
这里写点方法构建链表,和输出
public static void printListNode(ListNode head) { List list = new ArrayList(); ListNode temp = head; while(null != temp){ list.add(temp.val); temp = temp.next; } System.out.println(list); }
public static ListNode buildeListNode(int[] array) { ListNode head = null; //当前节点 ListNode temp = null; for (int i = 0;i< array.length;i++){ if(i == 0){ head = new ListNode(array[i]); temp = head; }else{ ListNode newNode = new ListNode(array[i]); temp.next = newNode; temp = newNode; } } return head; }