Given a linked list, remove the nth node from the end of list and return its head.
题目大意:
给定一个链表,删除它倒数第n位的节点并重新返回此链表
博主想到的方法比较简单,先遍历一次求出链表的长度,确定是正数第几个节点被删除,然后二次遍历删除它
方法一:
int length = 0; ListNode first = head; while(head != null){ length ++; head = head.next; } int index = length - n + 1; if(index == 1) return first.next; int count = 0; ListNode result = first; while(true){ count ++; if(index == count + 1){ first.next = first.next.next; return result; } first = first.next; } }} 网上介绍了另外一种方法比较直观,使用了双指针思想,但就运行速度来说都是O(n)class Solution { public ListNode removeNthFromEnd(ListNode head, int n) {
方法二:
定义两个指针相差n个节点,当p1指针指向末尾指针下一个时(null),删除p2节点下一个节点class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { int diff = 0; ListNode p1 = head; while(diff <= n){ p1 = p1.next; if(p1 == null ){ if(n == diff){ head.next = head.next.next; return head; }else return head.next; } diff++; } ListNode p2 = head; while(p1 != null){ p1 = p1.next; p2 = p2.next; } p2.next = p2.next.next; return head; } }