/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveNthFromEnd(head *ListNode, n int)*ListNode { // 遍历一次链表,记录表长Len if(head.Next == nil){ returnnil } Len := 1 Head := head for head.Next != nil{ head = head.Next Len++ } // 倒数第n个结点的前驱结点在表中为第 Len - n 个结点,将其前驱节点的后继指针指向被删结点的后继指针 head = Head if n == Len{ return head.Next } for i := 1;i < Len - n;i++{ head = head.Next } head.Next = head.Next.Next // 返回头结点 return Head }
funcremoveNthFromEnd(head *ListNode, n int)*ListNode { // 双指针实现 pre,rear := head,head // 快指针先走n步 for i:=0;i < n;i++{ if rear == nil{ return head } rear = rear.Next } // 再快慢指针一起走,直到快指针走到尾 if rear == nil{ // 如果快指针走到nil,则删去第一个元素 return head.Next } for rear.Next != nil{ pre = pre.Next rear = rear.Next } pre.Next = pre.Next.Next // 删去倒数第N个结点 return head }
1 2 3 4 5 6 7 8 9 10 11 12
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { dummy := &ListNode{0, head} first, second := head, dummy for i := 0; i < n; i++ { first = first.Next } for ; first != nil; first = first.Next { second = second.Next } second.Next = second.Next.Next return dummy.Next }
var a int = 0 funcremoveNthFromEnd(head *ListNode, n int) *ListNode { if head == nil{ returnnil } head.Next = removeNthFromEnd(head.Next,n) a++ if a == n{ return head.Next } return head }