最近面试笔试白板写代码,发现自己连链表都不会构建,放在这里防止自己再忘记
public class ListNode<T> {
T val;
ListNode next;
ListNode(T x){
this.val=x;
}
}
import java.util.ArrayList;
import java.util.List;
public class SingleList<T> {
ListNode<T> head;
SingleList(){
this.head=new ListNode<T>(null);
}
//尾插法
public ListNode createList(Integer[] element){
if(element==null){
return null;
}
ListNode<Integer> head=new ListNode<Integer>(0);
ListNode p=head;
for(int i=0;i<element.length;i++){
ListNode<Integer> temp=new ListNode<Integer>((Integer)element[i]);
p.next=temp;
p=p.next;
}
return head;
}
}
import javax.swing.*;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Solution solution=new Solution();
//调用方法
Integer[] data={1,2,3,2,2,2,5,4,2};
SingleList<Integer> list=new SingleList<Integer>();
ListNode<Integer> head =list.createList(data);
ListNode<Integer> p=head.next;
while(p!=null){
System.out.print(p.val+",");
p=p.next;
}
}
}