之前学链表的时候是用C语言,今天尝试手写了一版Java版本的链表的基本操作,在此记录一下。
挑了几个经常出现的方法如添加元素、遍历链表、反转链表等实现了一下,as follow:
package leetcode;
import org.junit.Test;
/**
* 链表的基本操作
* @author jsyuger
* 2021年11月16日
*/
public class BasicLinkNode {
Node head ;
/**
* 链表的实体类
* @author jsyuger
* 2021年11月16日
*/
class Node{
int data; //当前节点的数据
Node next; //当前节点的指针指向的下一个节点
public Node(){}
public Node(int data){
this.data=data;
}
public Node(int data,Node next){
this.data=data;
this.next=next;
}
}
/**
* 添加链表的节点
* @param data
* @return
*/
public Node addNode(int data){
if(head==null) return head = new Node(data); //空链表则返回一个节点的新链表
Node temp = head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=new Node(data); //尾插法,将元素添加到链表末尾
return head ;
}
/**
* 链表的遍历
* @param list
*/
public void printNode(Node list){
if(list==null) System.out.print("[]");
Node temp=list;
while(temp!=null){
System.out.print(temp.data+" -> "); //获取元素数据
temp=temp.next; //指针后移
}
}
/**
* 链表的反转
* @param head
* @return
*/
public Node reverseList(Node head) {
if(head==null||head.next==null) return head;
Node currTemp = head ; //当前节点
Node preTemp = null ; //当前节点的前一节点
while(currTemp!=null){
Node newTemp = currTemp.next ; //1、将当前节点的下一个节点临时储存到newTemp
currTemp.next = preTemp ; //2、关键操作,将当前节点的指针指向前一个节点
preTemp = currTemp ; //3、当前节点的前一个节点后移一位
currTemp = newTemp ; //4、当前节点后移一位
}
return preTemp ; //preTemp此时已经移动到了最后一个节点的位置,实现了倒序返回
}
@Test
public void test(){
//向链表head添加10个元素
int i=1;
while(i<=6){
addNode(i);
i++;
}
//遍历链表
printNode(head);
System.out.println();
//反转链表
head = reverseList(head);
//遍历反转后的链表
printNode(head);
System.out.println();
}
}