listNode 节点类
1 成员变量:val next
2 构造函数
package byteDance_test;
public class listNode {
char val;
listNode next;
listNode(char val){
this.val = val;
}
}
linkList 链表类
1 成员变量:head、tail节点,size
2 构造函数
3 添加元素函数
4 简单的显示函数
5 反转函数
package byteDance_test;
public class linkList {
listNode head;
listNode tail;
int size;
linkList(){
head = null;
tail = null;
size = 0;
}
public void add (listNode node){
if(head == null){
head = node;
tail = node;
size++;
}
else {
tail.next = node;
tail = node;
size++;
}
}
public void display(){
listNode cur = head;
while (cur!=null){
System.out.println(cur.val+"->");
cur=cur.next;
}
}
public void reverseLink(){
listNode cur = head;
listNode prev = null;
while (cur!=null){
listNode Next = cur.next;
cur.next = prev;
prev = cur;
cur = Next;
}
head = prev;
}
}
反转函数
变量使用 listNode:cur、next、prev
1 prev 初始化为null,作为最终的尾节点
2 cur 从head 开始遍历 ,将其next 指向prev, 然后依次向后移动prev和cur
public void reverseLink(){
listNode cur = head;
listNode prev = null;
while (cur!=null){
listNode Next = cur.next;
cur.next = prev;
prev = cur;
cur = Next;
}
head = prev;
}
主函数验证
package byteDance_test;
public class main {
public static void main(String[] args) {
listNode node_1 = new listNode('a');
listNode node_2 = new listNode('b');
listNode node_3 = new listNode('c');
listNode node_4 = new listNode('d');
listNode node_5 = new listNode('e');
linkList list = new linkList();
list.add(node_1);
list.add(node_2);
list.add(node_3);
list.add(node_4);
list.add(node_5);
list.display();
System.out.println("----------");
list.reverseLink();
list.display();
}
}