Leetcode: Remove Nth Node From End of List

题目: Given a linked list, remove the nth node from the end of list and return its head.

For example, Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note: Given n will always be valid. Try to do this in one pass.

思路分析: 双指针,前后两个指针之间的距离为n-1,当后一个指针指向链表末尾结点的时候,前一个指针指向的结点就是要删除的结点。

C++参考代码:

/** * Definition for singly-linked list. * struct ListNode { *int val; *ListNode *next; *ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public:ListNode *removeNthFromEnd(ListNode *head, int n){if (!head) return nullptr;int count = 1;ListNode *previous = nullptr;//指向front元素前面的结点ListNode *front = head;//前面的指针,指向要删除的结点ListNode *back = head;(count < n){back = back->next;count++;}//将back指针一直移动到;链表最末尾while (back->next){previous = front;front = front->next;back = back->next;}//如果previous不为空,则将previous指针的next指向front的next,即将front删除if (previous){previous->next = front->next;}//如果previous为空,,说明删除的是第一个位置的结点即头结点else{head = head->next;}front = nullptr;return head;}};

C#参考代码:

/** * Definition for singly-linked list. * public class ListNode { *public int val; *public ListNode next; *public ListNode(int x) { val = x; } * } */{public ListNode RemoveNthFromEnd(ListNode head, int n){if (head == null) return null;ListNode previous = null;ListNode front = head;ListNode back = head;for (int i = 0; i < n – 1; i++){back = back.next;}while (back.next != null){previous = front;front = front.next;back = back.next;}if (previous != null){previous.next = front.next;}else{head = head.next;}front = null;return head;}}

Python参考代码:

::if not head:return Noneprevious = Nonefront = headback = headcount = 1while count < n:back = back.nextcount += 1while back.next:previous = frontfront = front.nextback = back.nextif previous:previous.next = front.nextelse:head = head.nextdel frontreturn head

一个人骑行,孤单却内省;一群人骑行,壮观而有力。

Leetcode: Remove Nth Node From End of List

相关文章:

你感兴趣的文章:

标签云: