剑指offer 18 删除链表的节点(gt版本)

github版本,单指针(此方法非常巧妙),cur是被删除节点的前一个节点,当cur.next不为空时把cur.next.next赋给cur.next。 不用判断cur.next.next是否为空,就算它为空,说明待删除节点是尾结点,cur.next.next为null,将null赋给cur.next即删除了尾结点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) return null;
        if (head.val == val) return head.next;
        ListNode cur = head;
        while (cur.next != null && cur.next.val != val)
            cur = cur.next;//循环至cur.next节点是待删除节点
        if (cur.next != null)
            cur.next = cur.next.next;
        return head;

    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务