Lintcode:删除链表中倒数第n个节点

版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/91454562

问题:

给定一个链表,删除链表中倒数第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:这两种方法不不能等同!

猜你喜欢

转载自blog.csdn.net/pianzang5201/article/details/91454562