删除单链表指定元素
2016-06-13 21:40
369 查看
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } ListNode(int x, ListNode next) { val = x; this.next = next; } } public class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null) return null; ListNode dummyHead = new ListNode(0); ListNode tail = dummyHead; while (head != null) { if (head.val != val) { tail.next = head; tail = tail.next; } head = head.next; } tail.next = null; return dummyHead.next; } public ListNode removeElements2(ListNode head, int val) { if (head == null) return null; ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode pre = dummyHead; ListNode curr = head; while (curr != null) { if (curr.val == val) { pre.next = curr.next; } else { pre = pre.next; } curr = curr.next; } return dummyHead.next; } public ListNode removeElements3(ListNode head, int val) { if (head == null) return null; head.next = removeElements2(head.next, val); return head.val == val ? head.next : head; } public ListNode removeElements4(ListNode head, int val) { if (head == null) return null; ListNode newHead = new ListNode(0); ListNode savedHead = newHead; newHead.next = head; while (newHead.next != null) { if (newHead.next.val == val) { newHead.next = newHead.next.next; } else { newHead = newHead.next; } } return savedHead.next; } public static void print(ListNode head) { while (head != null) { System.out.print(head.val + " "); head = head.next; } System.out.println(); } public static void main(String[] args) { ListNode _4 = new ListNode(3, null); ListNode _3 = new ListNode(3, _4); ListNode _2 = new ListNode(2, _3); ListNode _1 = new ListNode(1, _2); ListNode head = new ListNode(1, _1); ListNode result = new Solution().removeElements(head, 1); print(result); } }
相关文章推荐
- C#定义并实现单链表实例解析
- C#数据结构之单链表(LinkList)实例详解
- C语言实现单链表逆序与逆序输出实例
- C语言单链表常见操作汇总
- C数据结构之单链表详细示例分析
- C++中单链表的建立与基本操作
- 深入单链表的快速排序详解
- C语言创建和操作单链表数据结构的实例教程
- C语言单链表的实现
- 浅谈PHP链表数据结构(单链表)
- java实现单链表中是否有环的方法详解
- java实现单链表、双向链表
- Python单链表的简单实现方法
- Python单链表简单实现代码
- Go语言单链表实现方法
- 浅谈PHP链表数据结构(单链表)
- Python单链表简单实现代码
- 结构之美:在单链表指定位置插入数据
- 《编程之美》3.4:没有头结点的单链表如何删除结点
- 结构之美:使用尾插法创建单链表