码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[203]-Remove Linked List Elements

时间:2015-06-10 12:28:49      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:val   remove   for   return   value   

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.


分析:

  • 如果链表不为空,保证第一个节点不等于val,如果等于,直接跳到下一个节点;
  • 如果此时链表为空,返回该链表;
  • 将头结点赋值给一个临时节点,如果该节点的下一个节点不为空,递归遍历;

    • 如果下一个节点的值等于给定值,直接跳到下下个节点;
    • 如果下一个节点的值不等于给定值,则让跳到下个节点再来循环;
  • 最后返回链表的头结点即可。

Code(c++):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head !=NULL && head->val == val) {
            head = head->next;
        }
        if(head == NULL) return head;
        ListNode* pre = NULL;
        pre = head;
        while(pre->next!=NULL){
            if(pre->next->val == val){
                pre->next = pre->next->next;
            } else{
                pre = pre->next;
            }
        }
        return head;
    }
};

Leetcode[203]-Remove Linked List Elements

标签:val   remove   for   return   value   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46438785

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!