[LintCode] 删除链表中倒数第n个节点
1 /** 2 * Definition of ListNode 3 * class ListNode { 4 * public: 5 * int val; 6 * ListNode *next; 7 * ListNode(int val) { 8 * this->val = val; 9 * this->next = NULL; 10 * } 11 * } 12 */ 13 class Solution { 14 public: 15 /** 16 * @param head: The first node of linked list. 17 * @param n: An integer. 18 * @return: The head of linked list. 19 */ 20 ListNode *removeNthFromEnd(ListNode *head, int n) { 21 // write your code here 22 ListNode* pre = head; 23 ListNode* cur = head; 24 for (int i = 0; i < n; i++) 25 cur = cur -> next; 26 if (!cur) { 27 delete pre; 28 return pre -> next; 29 } 30 while (cur -> next) { 31 pre = pre -> next; 32 cur = cur -> next; 33 } 34 delete pre -> next; 35 pre -> next = pre -> next -> next; 36 return head; 37 } 38 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步