首页 > 其他 > 详细

leetcode Remove Linked List Elements 203

时间:2015-05-22 13:35:59      阅读:118      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!