leetcode题解-19. Remove Nth Node From End of List

来源:互联网 发布:seo牛人 编辑:程序博客网 时间:2024/05/22 04:54

题意:给一个链表和数字n,移除倒数第n个数,返回head。

例子:
给定链表 1->2->3->4->5, 并且n = 2.
返回链表 1->2->3->5.

分析:题目比较简单,就是数据结构中链表的常规删除操作而已。需要注意的是,有可能删除的是头结点,因此需要声明头节点的前置节点dummyNode。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        if(head == null || head.next == null) return null;        int len = 0;        ListNode dummyNode = new ListNode(0);        dummyNode.next = head;        ListNode fastNode = head;        ListNode slowNode = dummyNode;        while(fastNode != null){            len++;            fastNode = fastNode.next;        }        for(int i = 0; i < len - n; i++){            slowNode = slowNode.next;        }        slowNode.next = slowNode.next.next;        return dummyNode.next;    }}
阅读全文
0 0
原创粉丝点击