Remove Linked List Elements

来源:互联网 发布:如何查看h3c端口 编辑:程序博客网 时间:2024/06/03 17:26

Description:

Remove all elements from a linked list of integers that have value val.

问题描述:

删除链表中所有某特定值的元素。给定链表的头结点和指定的值,编写函数返回处理过的链表的头结点。

Ex:

Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

解法一:

思路:

首先进行特殊条件检查,排查空链表的情况。另外如果头结点为待删除的值,直接删掉。先将头结点赋值给临时结点,再进行循环,找到该值就跳过该结点,否则继续遍历结点查找。

code:

/** * 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) {        if (head == null) {            return null;        }        ListNode temp = head;        while (temp.next != null) {            if (temp.next.val == val) {                temp.next = temp.next.next;            } else {                temp = temp.next;            }        }        if (head.val == val) {            head = head.next;        }        return head;    }}
0 0
原创粉丝点击