首页
IT
登录
6mi
u
盘
搜
搜 索
IT
19. Remove Nth Node From End of List
19. Remove Nth Node From End of List
xiaoxiao
2021-03-25
90
/** * 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; } } };
转载请注明原文地址: https://ju.6miu.com/read-12574.html
技术
最新回复
(
0
)