用Java实现单链表

public class ListNode{

    int val;

    ListNodenext;

    ListNode(int x){val = x;}

    public static class LinkedList{

        ListNode head;

    }

    public static LinkedList createLN(LinkedList list,int data){

        ListNode new_node =new ListNode(data);

        new_node.next=null;

        if(list.head==null){

            list.head=new_node;

        }

        else {

            ListNode last = list.head;

            while (last.next!=null){

            last=last.next;

        }

        last.next=new_node;

    }

    return list;

    }

    public static void printList(LinkedList list) {

        ListNode currNode = list.head;

        System.out.print("LinkedList: ");

        while (currNode !=null) {

            System.out.print(currNode.val +" ");

            currNode = currNode.next;

            }

    }

    public static void main(String[] args){

        int[] index = {1,2,3,3,2,1};

        LinkedList list =new LinkedList();

        for (int i=0;i

            createLN(list,index[i]);

        }

        printList(list);

    }

}

你可能感兴趣的:(用Java实现单链表)