emove all elements from a linked list of integers that have value val.java
Example:git
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
實現:github
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));
這裏寫點方法構建鏈表,和輸出ui
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; }
git:https://github.com/woshiyexinjie/leetcode-xin/tree/master/src/main/java/com/helloxin/leetcode/algorithms code