题目:
解答:
使用两个链表指针,一前一后运动,间隔n即可
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *p = head,*q1 = head,*q2;
for( int i = 0;i < n;++i )
p = p -> next;
if( p == NULL ) return head -> next;
while( p != NULL ) {
q2 = q1;
p = p -> next;
q1 = q1 -> next;
}
q2 -> next = q1 -> next;
return head;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)