Remove Nth Node From End of List:Given a linked list, remove the nth node from the end of list and return its head.For example:
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
题意:删除给定链表倒数第n个结点。
思路:其实本题比较常规的思路是先遍历链表求得链表的长度,然后在进行删除操作。另外一种思路是定义两个指针left和right,right先移动n步,如果right为null,则表示要删除的是头结点,此时直接返回head.next即可。如果first指针不为null,则两个指针一起移动,直到right为最后一个结点为止,left指向的即是要删除结点的前一个结点,可以直接执行left.next=left.next.next操作即可删除倒数第n个结点。
代码:
public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return null; ListNode p = head; ListNode q = head; for(int i=0;i<n;i++){ q=q.next; } if(q==null){ head = head.next; p = null; return head; } while(q.next!=null){ p = p.next; q = q.next; } ListNode temp = p.next.next; p.next = temp; return head; }