2015年7月22日 星期三

LeedCode:Remove Linked List Elements

題目:

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
找到含有目標值的節點並刪除。
Delete Node in a Linked List中的Linked List定義相同

想法:

這題也卡了有點久,原本是想設一個tempNodePointer指向開頭或結尾的節點,檢查完有目標值就刪掉換下一個,但問題出在,如果沒有目標值,只是純粹換下一個,會把原本的節點給蓋掉。
所以後來選擇比較不直觀的遞迴解。

Accepted Solution:

C#
  1. public class Solution {
  2. public ListNode RemoveElements(ListNode head, int val) {
  3. if (head!=null) //該點為空直接傳回null
  4. {
  5. while(head.val == val) //如果該點含目標值
  6. {
  7. //刪掉該點
  8. if(head.next!=null)head = head.next;
  9. else {
  10. head=null;
  11. return null;
  12. }
  13. }
  14. //對該點的下一點做同樣的事
  15. head.next=RemoveElements(head.next, val);
  16. }
  17. else return null;
  18. return head;
  19. }
  20. }

沒有留言:

張貼留言