LeetCode 19删除链表的倒数第N个节点-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 19删除链表的倒数第N个节点-中等
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個鏈表,刪除鏈表的倒數第 n 個結點,并且返回鏈表的頭結點。
進階:你能嘗試使用一趟掃描實現嗎?
輸入:head = [1,2,3,4,5], n = 2
輸出:[1,2,3,5]
示例 2:
輸入:head = [1], n = 1
輸出:[]
示例 3:
輸入:head = [1,2], n = 1
輸出:[1]
提示:
鏈表中結點的數目為 sz 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz代碼如下:
/*** 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 *dummy = new ListNode;ListNode *cur = dummy;cur->next = head;int len = getlength(head);for (int i = 1;i<len-n+1;i++){cur = cur->next;}cur->next = cur->next->next;ListNode *idx = dummy->next;delete dummy;return idx;}int getlength(ListNode *head){int len = 0;while(head){head = head->next;len++;}return len;} };總結
以上是生活随笔為你收集整理的LeetCode 19删除链表的倒数第N个节点-中等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软高管暗示 Copilot(原 Bin
- 下一篇: LeetCode 142环形链表||-中