/** * 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。