leetcode: (19) Remove Nth Node From End of List

来源:互联网 发布:小米3破解4g网络 编辑:程序博客网 时间:2024/06/06 07:44

【Question】

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个节点

首先,必须就算出一共有多少节点,才能知道要删除的节点的位置,通过一次遍历,计算出总的节点数;

然后,再一次遍历到倒数第n个节点的前一个节点,然后进行删除操作;

其中要注意的是

1)n=总的节点数 时 ,此时要删除的节点为首指针,只需将head=head->next;即可

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode *cur,*p,*temp,*pre;        p=head;        cur=head;        int count=0;        while(p!=NULL)        {            p=p->next;            count++;        }temp=(ListNode *)malloc(sizeof(ListNode));        if (count==n) {head=head->next;;return head;}        else        {            for(int i=0;i<count-n;i++)            {pre=cur;                cur=cur->next;            }              temp=pre->next;  pre->next=temp->next;  free(temp);        }        return head;    }};

Runtime: 4 ms

方法二:由于倒数第n个点到头结点的距离=第n个点的距离到尾节点的距离,所以不必进行第一次遍历得出总的节点数.

public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {    ListNode curr = head;      ListNode pre = head;      for(int i = 0;i < n;i++)          curr = curr.next;      if(curr == null)          return head.next;      while(curr.next != null)      {          curr = curr.next;          pre = pre.next;      }      pre.next = pre.next.next;      return head;      }   }
Runtime: 272 ms




0 0
原创粉丝点击