leetcode解题之移除链表元素

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

方法比较简单,新建一个链表,遍历原链表,将不等于目标值的节点放到新的链表中

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode ansList = new ListNode(0);
        ListNode temList=ansList;
        while(head!=null){
            if(head.val!=val){
                temList.next=new ListNode(head.val);
                temList=temList.next;
            }
            head=head.next;
        }   
        return ansList.next;
    }
}

快慢指针(哨兵),参看官方题解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode temNode = new ListNode(0);
        temNode.next=head;
        ListNode preNode =temNode,curNode=head;
     while(curNode!=null){
         if(curNode.val==val) preNode.next=curNode.next;
         else preNode=curNode;
         curNode=curNode.next;
     }
     return temNode.next;
    }
}
发布了98 篇原创文章 · 获赞 0 · 访问量 4010

猜你喜欢

转载自blog.csdn.net/l888c/article/details/104310586