链表


数据结构与算法之链表:

public class Code01_ReverseList {

    public static class Node{
        public int value;
        public Node next;

        public Node(int data){
            value = data;
        }
    }

    public static class DoubleNode{
        public int value;
        public DoubleNode last;
        public DoubleNode next;

        public DoubleNode(int data){
            value = data;
        }
    }

    //反转单链表
    public static Node reverseLinkedList(Node head){
        Node pre = null;
        Node next = null;
        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    //反转双向链表
    public static DoubleNode reverseDoubleList(DoubleNode head){
        DoubleNode pre = null;
        DoubleNode next = null;
        while (head != null){
            next = head.next;
            head.next = pre;
            head.last = next;
            head = next;
        }
        return pre;
    }

    //删除指定元素
    public static Node removeValue(Node head,int num){
        while (head != null){
            if (head.value != num){
                break;
            }
            head = head.next;
        }
        //head来到不需要删除的第一个元素
        Node per = head;
        Node cur = head;
        while (cur != null){
            if (cur.value == num){
                per.next = cur.next;
            }else {
                per = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

文章作者:
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 !
  目录