
问题
删除链表中等于给定值 val 的所有节点。
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
Remove all elements from a linked list of integers that have value val.
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
示例
public class Program { public static void Main(string[] args) { var head = new ListNode(1) { next = new ListNode(2) { next = new ListNode(6) { next = new ListNode(3) { next = new ListNode(4) { next = new ListNode(5) { next = new ListNode(6) } } } } } }; var res = RemoveElements(head, 6); ShowArray(res); Console.ReadKey(); } private static void ShowArray(ListNode list) { var node = list; while(node != null) { Console.Write($"{node.val} "); node = node.next; } Console.WriteLine(); } private static ListNode RemoveElements(ListNode head, int val) { //创建一个根节点,以便统一处理所有节点,否则需要单独处理边界,会很麻烦 var virtualHead = new ListNode(0); virtualHead.next = head; //临时节点,用于存放每次移动的指针 var next = virtualHead; while(next.next != null) { if(next.next.val == val) { //找到需要删除的节点,将指针往后移动2位 next.next = next.next.next; } else { //找不到,直接往后移动指针 next = next.next; } } //返回除了根节点之外的所有节点 return virtualHead.next; } public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } }
以上给出1种算法实现,以下是这个案例的输出结果:
1 2 3 4 5
分析:
显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3826。