11
Leetcode 19.Remove Nth Node From End of List
source link: https://zxs.io/article/1171
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len = 0;
ListNode newhead = new ListNode(0);
newhead.next = head;
ListNode p = newhead;
while (null != p) {
len += 1;
p = p.next;
}
p = newhead;
int cnt = len - n - 1 ;
while (cnt != 0) {
p = p.next;
cnt--;
}
p.next = p.next.next;
return newhead.next;
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK