Lintcode:刪除鏈表中倒數第n個節點

問題:

給定一個鏈表,刪除鏈表中倒數第n個節點,返回鏈表的頭節點。

樣例:

Example 1:
	Input: list = 1->2->3->4->5->null, n = 2
	Output: 1->2->3->5->null


Example 2:
	Input:  list = 5->4->3->2->1->null, n = 2
	Output: 5->4->3->1->null

python:

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list.
    @param n: An integer
    @return: The head of linked list.
    """
    def removeNthFromEnd(self, head, n):
        # write your code here
        if head == None or n <=0:
            return head
        nodeList = []
        result = ListNode(0)
        curNode = result
        while head != None:
            nodeList.append(head.val)
            head = head.next
        del nodeList[-1*n]
        for i in range(len(nodeList)):
            curNode.next = ListNode(nodeList[i])
            curNode = curNode.next
        return result.next

C++:

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: The head of linked list.
     */
    ListNode * removeNthFromEnd(ListNode * head, int n) {
        // write your code here
        if(head == NULL || n <= 0)
        {
            return head;
        }
        ListNode *result = new ListNode(0);
        ListNode *curNode = result;
        stack<ListNode*> nodeStack;
        while(head != NULL)
        {
            nodeStack.push(head);
            head = head->next;
        }
        int nodeNum = nodeStack.size();
        for(int i = 0; i<nodeNum; i++)
        {
            if(i == n - 1)
            {
                nodeStack.pop();
                continue;
            }
            ListNode *tempNode = curNode->next;
            curNode->next = nodeStack.top();
            curNode->next->next = tempNode;
            nodeStack.pop();
        }
        return result->next;
    }
};

 

PS:這兩種方法不不能等同!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章