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.

算法:双指针

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null)
            return null;
        ListNode p=head;
        for(int i=1;i<n;i++){
            p=p.next;
        }
        ListNode s,q;
        s=null;
        q=head;
        while(p.next!=null){
            s=q;
            q=q.next;
            p=p.next;
        }
        if(s==null)
            return q.next;
        s.next=q.next;
        q.next=null;
        q=null;
        return head;
    }
}

c++:

/**
 * 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)
            return NULL;
        ListNode *p,*q,*s;
        p=head;
        // head已遍历,k从1开始
        int k=1;
        while(k<n){
            p=p->next;
            k++;
        }
        q=head;
        s=NULL;
        while(p->next){
            s=q;
            q=q->next;
            p=p->next;
        }
        if(s){
            s->next=q->next;
            delete q;
            return head;
        }
        // 一个节点,而且n==1
        return q->next;
    }
};



posted @ 2014-11-13 16:16  bingtel  阅读(130)  评论(0编辑  收藏  举报