Guest User

Untitled

a guest
Nov 20th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. int Length(ListNode *l) {
  12. int count = 0;
  13. ListNode *p = l;
  14. while (p != NULL) {
  15. count++;
  16. p = p->next;
  17. }
  18. return count;
  19. }
  20.  
  21. ListNode* removeNthFromEnd(ListNode* head, int n) {
  22. ListNode *pre_remove = head, *remove;
  23. int length = Length(head);
  24. if (length - n == 0) {
  25. return pre_remove->next;
  26. }
  27. int flg = 1;
  28. while (flg < length - n) {
  29. pre_remove = pre_remove->next;
  30. flg++;
  31. }
  32.  
  33. remove = pre_remove->next;
  34. pre_remove->next = remove->next;
  35. remove = NULL;
  36. return head;
  37. }
  38. };
Add Comment
Please, Sign In to add comment