java单链表学习
在做单链表相关数据结构时,需要注意首尾。
/**
* @ Author : LHZ
* @ Data : Created in 21:44 2021/8/10
* @ Description: 单链表
* @ Version : 1.8
*/
public class TestDemo1 {
public static void main(String[] args) {
MySingleLinkList mySingleLinkList = new MySingleLinkList();
mySingleLinkList.addFirst(2);
mySingleLinkList.addLast(1);
mySingleLinkList.addLast(1);
mySingleLinkList.addLast(2);
System.out.println(mySingleLinkList.chkPalindrome(mySingleLinkList.head));
}
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
class MySingleLinkList {
Node head;
public MySingleLinkList() {
this.head = null;
}
public int size() {
//返回单链表长度
int temp = 0;
Node cur = this.head;
while (cur != null) {
temp++;
cur = cur.next;
}
return temp;
}
public void display() {
//遍历单链表
Node cur = this.head;
while (cur != null) {
System.out.println(cur.data);
cur = cur.next;
}
}
public void clear() {
this.head = null;
}
public void addFirst(int data) {
//头插法
Node cur = new Node(data);
if (this.head == null) {
this.head = cur;
return;
}
cur.next = this.head;
this.head = cur;
}
public void addLast(int data) {
//尾插法
Node temp = new Node(data);
if (this.head == null) {
this.head = temp;
return;
}
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = temp;
}
public void reverseList() {
//头插法逆置链表
if (size() <= 1) {
return;
}
Node cur = this.head.next;
this.head.next = null;
while (cur != null) {
Node curnext = cur.next;
cur.next = this.head;
this.head = cur;
if (curnext == null) {
return;
}
cur = curnext;
}
}
public void reverseList2() {
//前后节点逆置单链表
Node prev = null;
Node cur = this.head;
Node curnext = null;
while (cur != null) {
curnext = cur.next;
if (curnext == null) {
cur.next = prev;
this.head = cur;
return;
}
cur.next = prev;
prev = cur;