* 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); }
intget_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; } };
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
classSolution(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 defsumOfList(self,head): temp = head res = 0 while temp isnotNone: res+=1 temp = temp.next return res defremoveNthFromStart(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
近期评论