1.定义一个简单链表
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
2.链表操作: 新增、遍历展示
public class Solution{
private ListNode head;
//向链表末尾增加元素
public void addEle(int val) {
//如果头节点为空,则新建头节点
if (head == null) {
head = new ListNode(val);
} else {
//头节点不为空,则复制一份链表,将复制的链表指针移到链表尾部。
ListNode listNode = head;
while (listNode.next != null) {
listNode = listNode.next;
}
listNode.next = new ListNode(val);
}
}
public void show() {
if (head == null) {
System.out.println("Link is empty.");
} else {
ListNode listNode = head;
while (listNode != null) {
System.out.println("val is: " + listNode.val);
listNode = listNode.next;
}
}
}
}
3.结果展示
public static void main(String[] args) {
Solution so = new Solution();
so.addEle(3);
so.addEle(7);
so.addEle(32);
so.addEle(89);
so.show();
}
4.牛客剑指offer题目 从尾到头打印链表
4.1方法一:
思路:利用栈先进后出的特点,将链表中的元素放入栈中,再遍历栈放入Array List中
public ArrayList<Integer> printListFromTailToHead() {
ArrayList<Integer> res = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
if(head==null){
return res;
}
ListNode listNode = head;
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.empty()){
res.add(stack.pop());
}
return res;
}
4.2 方法2:
利用ArrayList.add(0,val);
public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
//method 1: use
ArrayList<Integer> arrayList = new ArrayList<>();
while (listNode != null) {
arrayList.add(0,listNode.val);
listNode = listNode.next;
}
return arrayList;
}
4.3 方法3:
利用递归
效率不高
public ArrayList<Integer> printListFromTailToHead3(ListNode listNode) {
if (listNode != null) {
printListFromTailToHead3(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
努力,进取,奋斗!