Remove Linked List Elements(leetcode203)
阿新 • • 發佈:2018-11-28
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; }
git:https://github.com/woshiyexinjie/leetcode-xin/tree/master/src/main/java/com/helloxin/leetcode/algorithms