删除链表的倒数第n个节点
删除链表的倒数第n个节点
http://www.nowcoder.com/questionTerminal/f95dcdafbde44b22a6d741baf71653f6
题目链接:https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=190&&tqId=35195&rp=1&ru=/activity/oj&qru=/ta/job-code-high-rd/question-ranking
因为是删除倒数第n个节点,所以首先遍历链表的长度,之后再把循环出正数第length-n个节点,将p节点的next域指向p.next.next地址
public ListNode removeNthFromEnd (ListNode head, int n) { // write code here ListNode cur=head; int len=0; while(cur!=null){ cur=cur.next; ++len; } if(len==n) return head.next; cur=head; int temp=len-n; while(temp>1){ cur=cur.next; temp--; } cur.next=cur.next.next; return head; }