链表

链表

链表是一种物理存储单元上非连续,非顺序的存储结构,数据元素的逻辑指针是通过链表中的指针链接次序实现的,链表由一系列节点(链表的每一个元素称为一个节点)组成,节点可以在运行的时候动态生成.每一个节点包括两个部分,一个是存储数据元素的数据域,另一个是存储下一个节点地址的指针域

链表的创建:

class Link(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

删除某一个链表的值为val的节点:

class Solution:
    """
    @param head: a ListNode
    @param val: An integer
    @return: a ListNode
    """
    def removeElements(self, head, val):
        # write your code here
        if head is None:
            return None
        new_link = Link(0)##链表全部的节点可能都存在等于val的值,所以需要添加一个节点
        new_link.next = head
        head = new_link
        pre = head
        while pre.next is not None:  # 遍历链表,删除等于val的所有节点
            if pre.next.val == val:
                pre.next = pre.next.next
            else:
                pre = pre.next
        return new_link.next
chain=(3,Link(5,Link(2,Link(5,Link(0))))) link
=Solution().removeElements(chain,3)

删除链表倒数第n个结点:

class  Solution():
    def  nthnode(self,head,n):
        front=back=head
        for   i in range(n):
            front=front.next##得到前面的n个结点
        while  (front):
            front=front.next##
            back=back.next
        return  back

翻转链表

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        if   head is  None  and  head.next  is  None:
            return  head
        new_head=self.reverse(head.next)##一直递归到最后的位置为止
        head.next.next=head.next##对head进行操作
        head.next=None##断开当前链表的下一个结点
        return    new_head
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/10419694.html