leetcode-华为专题-19. 删除链表的倒数第 N 个结点
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* H = new ListNode(); // 加一个头节点,避免了对只有一个节点情况的判断 H->next = head; int len = getlen(H); if(head==0) return NULL; int cnt = len - n-1; ListNode* p = H; while(cnt--){ p = p->next; } // cout<<"val: "<<p->val<<endl; p->next = p->next->next; return H->next; } int getlen(ListNode* head){ if(head==NULL) return 0; int count = 0; while(head){ count++; head = head->next; } return count; } };