leetcode: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.
Note:
Given n will always be valid.
Try to do this in one pass.
分析:题意为给一个链表,删除链表末端第n个节点然后返回头节点。
思路:利用双指针思想,两个指针之间间隔n-1,每个指针相后走一步,直到后面一个指针没有后继元素,此时前一个指针就是所要删除的节点。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(head==NULL) return NULL; ListNode *p,*q,*temp; p=head; q=head; temp=NULL; for(int i=0; i<n-1; i++){ q=q->next; } while(q->next){ temp=p; q=q->next; p=p->next; } if(temp==NULL){ //这种情况下,即n=1,删除的是头节点 head=p->next; delete p; } else{ temp->next=p->next; delete p; } return head; } };
朱颜辞镜花辞树,敏捷开发靠得住!