单链表的实现:

分为java和python两种代码:

Python代码如下:

# -*- coding: utf-8 -*-

'''
利用python实现单向链表,单向链表由数据部分和下节点地址两部分组成
    对于单向链表,首先要对每个链表元素创建一个类,属性包含数据部分和下节点地址部分。
    然后再创建一个类来表示单向链表,单项列表主要包含,初始化,判断是否为空,追加节点,删除节点,插入节点,更新节点,
    根据索引值获取数据项,根据数据项获取索引值,清空链表操作。
'''

# 定义单链表的节点Node类
class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next
    def __repr__(self):
        # 覆写了object中的__repr__,直接输出Node类对象即为调用了这个函数
        return str(self.data)

# 定义单链表类SingleChainTable
class SingleChainTable(object):
    def __init__(self):
        self.head = None
        self. length = 0
    
    def isEmpty(self):
        if self.length == 0:
            return True
        else:
            return False

    def append(self, dataOrNode):
        item = None
        # isinstance用来判断dataOrNode是否属于Node对象
        # 如果是,直接接到链表末尾,如果不是,将其构建为一个节点接到链表末尾
        if isinstance(dataOrNode, Node):
            item = dataOrNode
        else:
            item = Node(dataOrNode)

        # 首先要判断链表是否为空,如果为空,则直接把item赋给head
        # 否则,遍历链表找到最后一个节点
        if self.head == None:
            self.head = item
            self.length += 1
        else:
            node = self.head
            while node.next:
                node = node.next
            node.next = item
            self.length += 1

    # 根据索引值来删除链表,首先要判断链表是否为空,索引值是否超出链表范围
    # 如果以上两种情况都没出现,则查找索引值所对应的节点
    # 如果index所指的是头节点,则直接将头节点head更改为原头节点的下一个节点,并将长度减去1即可。
    # 如果index不是头节点,则需要遍历链表,找到index所对应的节点和其前一个节点,将前一个节点的next赋值为其后一个节点
    def delete(self, index):
        if self.isEmpty():
            print('the single chain table is empty.')
            return
        if index < 0 or index >= self.length:
            print('error: out of index.')
            return
        
        if index = 0:
            self.head = self.head.next
            self.length -= 1
            return
        
        j = 0
        node = self.head
        preNode  = self.head
        while node.next and j < index:
            preNode = node
            node = node.next
            j += 1

        if j == index:
            preNode.next = node.next
            self.length -= 1
            return

    # 这里将插入理解为在某个索引值所对应的节点之前插入,因此需要找到index对应节点和其前一个节点
    # 根据索引值插入节点,因此该函数需要一个索引值index,还需要一个节点对象dataOrNode
    # 因为有索引值,所以链表为空,不能插入,index也不能超过链表范围
    # 首先判断index是否为0,为0,直接把数据作为表头,否则遍历寻找index所对用节点
    def insert(self, index, dataOrNode):
        if self.isEmpty():
            print('the single chain table is empty.')
            return
        if index < 0 or index >= self.length:
            print('error: out of index.')
            return
        
        item = None
        if isinstance(dataOrNode, Node):
            item = dataOrNode
        else:
            item = Node(dataOrNode)

        if index == 0:
            item.next = self.head
            self.head = item
            self.length += 1
            return

        j = 0
        preNode = self.head
        node = self.head
        while node.next and j < index:
            preNode = node
            node = node.next
            j += 1
        
        if j == index:
            preNode.next = item
            item.next = node
            self.length += 1
            return

    # 更新索引值所对应节点的数据项
    # 拥有索引值index,因此需要判断
    def updata(self, index, data):
        if self.isEmpty():
            print('the single chain table is empty.')
            return
        if index < 0 or index >= self.length:
            print('error: out of index.')
            return
        
        j = 0 
        node = self.head
        while node.next and j < index:
            node = node.next
            j += 1

        if j == index:
            node.data = data
            return 

    # 根据索引值获取数据项
    # 判断index
    def getItem(self, index):
        if self.isEmpty():
            print('the single chain table is empty.')
            return
        if index < 0 or index >= self.length:
            print('error: out of index.')
            return
        
        j = 0
        node = self.head
        while node.next and j < index:
            node = node.next
            j += 1
        
        if j == index:
            return node.data

    # 判断数据项data是否在链表中,并返回index值
    def getIndex(self, data):
        if self.isEmpty():
            print('the single chain table is empty.')
            return

        j = 0
        node = self.head
        while node:
            if node.data = data:
                return j
            else:
                node = node.next
                j += 1

        if j == length:
            print('%s not found' % data)
            return

    def clear(self):
        self.head = None
        self.length = 0

 

Java代码如下:

public class SingleChainTable2 {

    private Node head;
    private int length;
    
    public SingleChainTable2() {
        this.head = null;
        this.length = 0;
    }
    
    public boolean isEmpty(){
        if(this.length == 0){
            return true;
        }else{
            return false;
        }
    }
    
    public void append(Object dataOrNode){
        Node item = null;
        if(dataOrNode instanceof Node){
            item = (Node)dataOrNode;
        }else{
            item = new Node(Integer.parseInt(dataOrNode.toString()));
        }
        if(this.isEmpty()){
            this.head = item;
            this.length++;
        }else{
            Node node = this.head;
            while(node.getNext() != null){
                node = node.getNext();
            }
            node.setNext(item);
            this.length++;
        }
        
    }
    
    public void delete(int index){
        if(this.isEmpty()){
            System.out.println("the single chain table is empty.");
        }
        if(index < 0 || index >= this.length){
            System.out.println("error: out of index.");
        }
        
        if(index == 0){
            this.head = this.head.getNext();
            this.length--;
        }
        
        int j = 0;
        Node preNode = this.head;
        Node node = this.head;
        while(node.getNext() != null && j < index){
            preNode = node;
            node = node.getNext();
            j++;
        }
        if(j == index){
            preNode.setNext(node.getNext());
            this.length--;
        }    
    }
    
    public void insert(int index, Object dataOrNode){
        if(this.isEmpty()){
            System.out.println("the single chain table is empty.");
        }
        if(index < 0 || index >= this.length){
            System.out.println("error: out of index.");
        }
        
        Node item = null;
        if(dataOrNode instanceof Node){
            item = (Node)dataOrNode;
        }else{
            item = new Node(Integer.parseInt(dataOrNode.toString()));
        }
        
        if(index == 0){
            item.setNext(this.head);
            this.head = item;
            this.length++;
        }
        
        int j = 0;
        Node preNode = this.head;
        Node node = this.head;
        while(node.getNext() != null && j < index){
            preNode = node;
            node = node.getNext();
            j++;
        }
        if(j == index){
            preNode.setNext(item);
            item.setNext(node);
            this.length++;
        }
    }
    
    public void update(int index, int data){
        if(this.isEmpty()){
            System.out.println("the single chain table is empty.");
        }
        if(index < 0 || index >= this.length){
            System.out.println("error: out of index.");
        }
        
        int j = 0;
        Node node = this.head;
        while(node.getNext() != null && j < index){
            node = node.getNext();
            j++;
        }
        if(j == index){
            node.setData(data);
        }
    }
    
    public int getItem(int index){
        if(this.isEmpty()){
            System.out.println("the single chain table is empty.");
            return -11111;
        }
        if(index < 0 || index >= this.length){
            System.out.println("error: out of index.");
            return -11111;
        }
        
        int j = 0;
        Node node = this.head;
        while(node.getNext() != null && j < index){
            node = node.getNext();
            j++;
        }
        return node.getData();
    }
    
    public int getIndex(int data){
        if(this.isEmpty()){
            System.out.println("the single chain table is empty.");
            return -1111;
        }
        
        int j = 0;
        Node node = this.head;
        while(node != null){
            if(node.getData() == data){
                return j; 
            }else{
                node = node.getNext();
                j++;
            }
        }
        if(j == length){
            System.out.println(data + "not found.");
        }
        return -1111;
    }
    
    public void clear(){
        this.head = null;
        this.length = 0;
    }
}

class Node extends Object{
    private int data;
    private Node next;
    
    public void setData(int data){
        this.data = data;
    }
    public void setNext(Node next){
        this.next = next;
    }
    public int getData(){
        return this.data;
    }
    public Node getNext(){
        return this.next;
    }
    
    
    public Node(int data){
        this.data = data;
        this.next = null;
    }
    public String toString(){
        return "" + this.data;
    }
}

 

 

Java和Python基本是一样的,只是语法上的不同,还有要注意,java中本类用this关键字,而python的本类用self关键字。