首页 > 其他 > 详细

203. 移除链表中的元素 Remove Linked List Elements

时间:2017-04-05 00:41:29      阅读:283      评论:0      收藏:0      [点我收藏+]

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

题意:移除链表中指定val的元素

注意:考虑删除节点在尾部,以及连续删除两个相邻节点的情况

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * public int val;
    5. * public ListNode next;
    6. * public ListNode(int x) { val = x; }
    7. * }
    8. */
    9. public class Solution {
    10. public void Delete(ListNode node) {
    11. node.val = node.next.val;
    12. node.next = node.next.next;
    13. }
    14. public ListNode RemoveElements(ListNode head, int val) {
    15. ListNode node = head;
    16. ListNode last = null;
    17. while (node != null) {
    18. if (node.val == val) {
    19. if (node.next != null) {
    20. Delete(node);
    21. continue;
    22. } else {
    23. if (last != null) {
    24. last.next = null;
    25. } else {
    26. return null;
    27. }
    28. }
    29. }
    30. last = node;
    31. node = node.next;
    32. }
    33. return head;
    34. }
    35. }






203. 移除链表中的元素 Remove Linked List Elements

原文:http://www.cnblogs.com/xiejunzhao/p/14a0f6f1947cc0296ea4571a136c64c4.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!