单向链表

//ADT
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; } }

public class List {
    //求链表的长度
    public int ListLength(ListNode HeadNode){
        int length = 0;
        ListNode currentNode = HeadNode;
        while (currentNode!=null){
            length++;
            currentNode = currentNode.getNext();
        }
        return length;
    }

    /**
     * 插入一个结点可以分为三种情况
     * 1、在链表的表头钱插入一个结点 修改一个next指针
     * 2、在链表的表尾插入一个结点 修改两个next指针
     * 3、在链表中甲随机插入 修改两个next指针
     */
    public 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("Insert invalid!");
            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;
    }
    /**
     * 删除分为三种情况
     * 1、删除第一个元素
     * 2、删除最后一个元素
     * 3、删除中间元素
     */
    public ListNode DeleteNodeFromLinkedlist(ListNode headNode,int position){
        int size = ListLength(headNode);
        if(position>size||position<1){
            System.out.println("Position invalid!");
            return headNode;
        }
        if(position == 1){
            ListNode currentNode = headNode.getNext();
            headNode=null;
            return currentNode;
        }
        else{
            ListNode previousNode = headNode;
            int count = 1;
            while(count<position-1){
                previousNode = previousNode.getNext();
                count++;
            }
            ListNode currentNode = previousNode.getNext();
            previousNode.setNext(currentNode.getNext());
            currentNode = null;
        }
        return headNode;
    }

    //删除单向链表
    public void DeleteLinkedList(ListNode head){
        ListNode auxilaryNode,iderator = head;
        while(iderator!=null){
            auxilaryNode=iderator.getNext();
            iderator=null;//释放结点
            iderator=auxilaryNode;
        }
    }
}

 

posted on 2018-01-26 21:57  ZhangのBlog  阅读(286)  评论(0编辑  收藏  举报