2016年2月20日 星期六

LEET code -- current

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


這題簡單
一開始先檢查 頭是不是要被刪除的

接著再檢查 current->next的值是不是


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    if(!head)return head;
    struct ListNode* current=head,*temp;
    
    while(head!=NULL && head->val==val){
        temp=head;
        head=head->next;
        free(temp);
    }
    current=head;
    while(current!=NULL && current->next!=NULL){//general case
        if(current->next->val==val){
            temp=current->next;
            current->next=temp->next;
            free(temp);
        }else{
            current=current->next;
        }
    }
    return head;
}

沒有留言:

張貼留言