Remove all elements from a linked list of integers that have value val
.
样例
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as 1->2->4->5
这道题的算法其实很简单,如果遇到要删除的元素,跳过,直接找到下一个非目标元素;无奈学渣的我对链表竟然已经到了如此退化的题目,所以也研究了一些时间。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param head a ListNode 12 * @param val an integer 13 * @return a ListNode 14 */ 15 public ListNode removeElements(ListNode head, int val) { 16 // Write your code here 17 ListNode helpnode = new ListNode (0); 18 helpnode.next = head; 19 ListNode p = helpnode; 20 while(p.next != null){ 21 if(p.next.val == val){ 22 p.next = p.next.next; 23 } 24 else { 25 p = p.next; 26 } 27 } 28 return helpnode.next; 29 } 30 }
拓展题:
删除排序链表中的重复元素
容易 删除排序链表中的重复元素查看运行结果
给定一个排序链表,删除所有重复的元素每个元素只留下一个
样例
给出1->1->2->null,返回 1->2->null
给出1->1->2->3->3->null,返回 1->2->3->null
1 /** 2 * Definition for ListNode 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param ListNode head is the head of the linked list 15 * @return: ListNode head of linked list 16 */ 17 public static ListNode deleteDuplicates(ListNode head) { 18 ListNode p = new ListNode(0); 19 p.next = head; 20 if(head == null ) 21 return null; 22 while (head.next != null){ 23 if (head.next.val == head.val ){ 24 head.next = head.next.next; 25 }else{ 26 head = head.next; 27 } 28 } 29 return p.next; 30 } 31 }
时间: 2024-11-07 10:13:06