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

leetcode Remove Linked List Elements 203

时间:2015-05-22 13:38:24      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:leetcode remove link

Remove Linked List Elements

 Total Accepted: 11291 Total Submissions: 42824

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 for adding this problem and creating all test cases.


翻译:移除一个整型链表中值为val的所有元素


解题思路:类似指针,一个前节点 preNode, 一个当前节点curNode ,当遇到值为val的节点时, 前节点preNode的下一节点直接指向当前节点 curNode的下一节点,即跳过值为val的节点   preNode.next=curNode.next 。


代码如下

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution
{
    public ListNode removeElements(ListNode head, int val)
    {
		ListNode temp = new ListNode(0);
		temp.next=head;
		ListNode preNode=temp;//设置前节点为空
		ListNode curNode=head;//设置当前节点为头节点
		while (curNode!=null)
		{
			if (curNode.val==val)
			{
				preNode.next=curNode.next;
			}
			else
			{
				preNode=preNode.next;
			}
			curNode=curNode.next;
		}
		return temp.next;
    }
}

 

leetcode Remove Linked List Elements 203

标签:leetcode remove link

原文地址:http://blog.csdn.net/zzc8265020/article/details/45914801

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