您好,登錄后才能下訂單哦!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void run(ListNode*head, int &num)//遍歷鏈表,得到鏈表的長度; { while (head != NULL) { num++; head = head->next; } } ListNode* removeNthFromEnd(ListNode* head, int n) { int num=0; if (head == NULL) return NULL; run(head, num); if (n > num) cout << "刪除位置不合法"; else { ListNode*p = NULL,*q=NULL; int i = 1; if (n == num)//刪除首結點; { q = head; head = head->next; delete q; } else//刪除的不是首結點 { q = head->next; p = head; while (i < num-n) { p = q; q = q->next; i++; } p->next = q->next; delete q; } return head; } } };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。