单向链表(Java实现)

2018-10-05  本文已影响0人  少寨主的互联网洞察
package com.cqu.Thread;

public class ListNode {
    private int data;
    private ListNode next;
    public ListNode(int data) {
        this.data=data;
    }
    public void setData(int data) {
        this.data=data;
    }
    public int getData() {
        return data;
    }
    public void setNext(ListNode next) {
        this.next=next;
    }
    public ListNode getNext() {
        return this.next;
    }
    //获取链表长度的函数 时间复杂度O(n),空间复杂度O(1)
    int ListLength(ListNode headNode) {
        int length=0;
        ListNode currentNode=headNode;
        while(currentNode!=null) {
            length++;
            currentNode=currentNode.next;
        }
        return length;
    }
    //链表插入操作,返回头节点,时间复杂度为O(n),空间复杂度为O(1)
    ListNode InsertInLinkedList(ListNode headNode,ListNode nodeToInsert,int position) {
        if(headNode==null) {
            return nodeToInsert;
        }
        int size=ListLength(headNode);
        if(position>size+1||position<1) {
            System.out.println("position of node to insert is invalid.The valid inputs are 1 to"+(size+1));
            return headNode;
        }
        if(position==1) {
            nodeToInsert.setNext(headNode);
            return nodeToInsert;
        }else {
            ListNode previousNode=headNode;
            int count=1;
            while(count<position-1) {
                previousNode=previousNode.getNext();
                count++;
            }
            ListNode currentNode=previousNode.getNext();
            nodeToInsert.setNext(currentNode);
            previousNode.setNext(nodeToInsert);
        }
        return headNode;
    }
    //删除链表当中的一个节点
    ListNode DeleteNodeFromLinkedList(ListNode headNode,int position) {
        int size=ListLength(headNode);
        if(position>size||position<1) {
            System.out.println("posiotion of node to delete is invalid, the valid inputs are 1 to"+size);
            return headNode;
        }
        if(position==1) {
            ListNode currentNode =headNode.getNext();
            headNode=null;
            return currentNode;
        }else {
            ListNode previousNode=headNode;
            int count=1;
            while(count<position) {
                previousNode=previousNode.getNext();
                count++;
            }
            ListNode currentNode=previousNode.getNext();
            previousNode.setNext(currentNode.getNext());;
            currentNode=null;
        }
        return headNode;
    }
    //删除单向链表
    void DeleteLinkedList(ListNode head) {
        ListNode auxilaryNode,iterator=head;
        while(iterator!=null) {
            auxilaryNode=iterator.getNext();
            iterator=null;//垃圾回收器将自动处理
            iterator=auxilaryNode;
        }
    }
}










上一篇 下一篇

猜你喜欢

热点阅读