当前位置: 首页 > 后端技术 > Java

LeetCode-203-移除链表元素

时间:2023-04-02 01:39:24 Java

移除链表元素题目描述:给你一个链表头节点head和一个整数val,请删除链表中所有满足Node.val==val的节点,并且返回一个新的头节点。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:链表遍历首先初始化一个节点firstNode指向头节点,cur指向头节点,last指向firstNode节点,然后开始遍历:firstcur不能为空;如果cur节点的值等于目标值val,则将last的next指向cur的next,将cur赋值给cur的next;如果cur节点的值不等于目标值val,则将last和cur节点向后移动一位。遍历之后返回给firstNode的下一个节点就是处理后的链表。publicclassLeetCode_203{publicstaticListNoderemoveElements(ListNodehead,intval){ListNodefirstNode=newListNode(-1);firstNode.next=head;ListNodecur=firstNode.next;ListNodelast=firstNode;while(cur!=null){if(cur.val==val){last.next=cur.next;当前=最后一个。下一个;}else{last=cur;cur=cur.next;}}返回firstNode.next;}publicstaticvoidmain(String[]args){ListNodehead=newListNode(1);head.next=newListNode(2);head.next.next=newListNode(6);head.next.next.next=newListNode(3);head.next.next.next.next=newListNode(6);删除元素(头,6);while(head!=null){System.out.print(head.val+"");head=head.next;}}}【每日留言】在这个不完美的世界里,勤奋有好报,懒惰必有罚。