leetcode-19-remove nth node from end of list

题目

删除链表的倒数第n个元素

分析

首先计算出链表的长度k,删除倒数第n个元素,实际就是删除正数第k-n+1个元素

C++代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode* (ListNode* head, int n) {
int len = get_ListNodeLength(head);
int k = len - n + 1;
return removeNthFromBegin(head, k);
}

int get_ListNodeLength(ListNode* head){
int len = 0;
while(head){
len++;
head = head->next;
}
return len;
}

ListNode* removeNthFromBegin(ListNode* head, int n){
ListNode* pre = head;
if(n == 1) return head->next;
for(int i = 0; i < n - 2; i++)
pre = pre->next;
pre->next = pre->next->next;
return head;
}
};

Python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def (self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""

num = self.sumOfList(head)
res = self.removeNthFromStart(head, num + 1 - n)
return res

def sumOfList(self,head):
temp = head
res = 0
while temp is not None:
res+=1
temp = temp.next
return res
def removeNthFromStart(self, head, n):
tmp_h = head
tmp_b = head
if n==1:
return head.next
else:
for i in range(n-1):
tmp_b = tmp_h
tmp_h = tmp_h.next
tmp_b.next = tmp_h.next
return head