【Leetcode】19. Remove Nth Node From End of List

来源:互联网 发布:云计算与大数据 编辑:程序博客网 时间:2024/06/05 00:29

方法一:

思路:

(1)若链表为空,直接返回null。

(2)求链表的长度len。

(3)若n==len,则删除的是第一个节点,直接删除后返回即可。

(4)从头开始遍历链表,找到待删除节点cur,并用pre记录其前驱结点。

(5)若pre不为空,说明删除的不是第一个节点,直接置pre.next=cur.next即可。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null)return null;ListNode cur = head, pre = null;int len = 0;while (cur != null) {cur = cur.next;len++;}if (n == len) {head = head.next;return head;}cur = head;for (int i = 0; i < len - n; i++) {pre = cur;cur = cur.next;}if (pre != null)   pre.next = cur.next;return head;}}

Runtime:15ms


方法二:双指针

思路:

(1)双指针:设置两个指针first跟second。

(2)first指针先移动n步。

(3)若first指针为空,则表示要删除的是头节点,此时直接返回head->next即可。

(4)first指针不为空,则将两个指针一起移动,直到first指针指向最后一个节点,令second->next=second->next->next即可。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null)return head;ListNode first = head, second = head;for (int i = 0; i < n; i++)first = first.next;if (first != null) {while (first.next != null) {first = first.next;second = second.next;}second.next = second.next.next;}elsehead = head.next;return head;}}

Runtime:15ms

1 0
原创粉丝点击