[List] LEETCODE19 delete the penultimate n nodes

// first solution, a traversal number length, connected end to end and then, once again traversed 
class Solution { 
public: 
    ListNode removeNthFromEnd * (* ListNode head, n-int) { 
        ListNode TEM * = head; 
        int len = 0; 
        the while ( tem-> next) {// this is the true length of the length obtained -1 
            TEM TEM- => Next; 
            len ++; 
        } 
        IF (len == 0) return NULL; 
        IF (len ==. 1) { 
            IF (n-== . 1) { 
                head-> Next = NULL; 
            } 
            the else head = head-> Next; 
            return head; 
        } 
        TEM-> Next = head; // connected end to end 
        ListNode * tail = tem;
        for (int i = 0; i <len-n + 1; i ++) {// departing from the last node, until the front reaches a node to be deleted; if you want to delete the node is the header, does not move
            = TEM- TEM> Next; 
        } 
        ListNode Trash * = TEM-> Next; // To delete a node 
        tail-> next = NULL; // if you want to delete the last, if not the penultimate sentence and will a ring header connected 
        TEM-> Next = trash-> Next; 
        IF (Trash == head) head = head-> Next; 
        tail-> Next = NULL; 
        return head; 
        
    } 
};

  

// The above classification is very difficult, and in fact, two pass, completely unnecessary 
// special case to avoid trouble free and involved head and tail, and good use of the method is an empty list head plus the Node 

class Solution { 
public : 
    ListNode removeNthFromEnd * (* ListNode head, n-int) { 
        ListNode dummy = new new ListNode * (0); 
        dummy-> Next = head; 
        ListNode head * = R & lt; 
        int len = 0; 
        the while (R & lt) { 
            R & lt R- = > Next; 
            len ++; 
        } 
        R & lt dummy =; 
        for (int I = 0; I <-n-len; I ++) { 
            R & lt = R-> Next; 
        } 
        R-> Next = R-> next-> Next; 
        return dummy- > Next; 

        
    } 
};

  

// Solution 3, made by traversing the two pointers, a first faster than the second n nodes, arrive a ranking when the tail, before the second is to delete a node. 
{Solution class 
public: 
    ListNode removeNthFromEnd * (* ListNode head, n-int) { 
        ListNode dummy = new new ListNode * (0); 
        dummy-> Next = head; 
        ListNode dummy = F *, S * = dummy; 
        for (int I = 0; I <n-; I ++) { 
            F = F-> Next; 
        } 
        the while (F-> Next) { 
            F = F-> Next; 
            S = S-> Next; 
        } 
        S-> Next = S-> next- > Next; 
        return dummy-> Next; 
    } 
};

  

Guess you like

Origin www.cnblogs.com/rarecu/p/11520482.html