/**
* 链表的操作
*/
public class ReverseOfLink {
public static void main(String[] args) {
int[] arr = {3, 3, 3, 2, 5, 8, 3, 5, 3, 3, 3, 9};
//Node head = generateDualLike(arr);
Node head = generateSingleLink(arr);
//list(head);
//Node node = reverseSingleLink(head);
//Node node = reverseDualLink(head);
Node node = removeNode(head, 3);
list(node);
}
/*可能会删除头部,链表中也可能有连续的删除节点,所以需要返回新的head*/
public static Node removeNode(Node head, int val) {
if(head == null){
return null;
}
//让head来到第一个不需要删除的节点
/*3, 3, 3, 2, 5, 8, 3, 5, 3, 3, 3, 9*/
while (head.val == val){
head = head.next;
}
/*节点变成: 2, 5, 8, 3, 5, 3, 3, 3, 9*/
//TODO: 实现删除逻辑
return head;
}
/*反转单项链表*/
public static Node reverseSingleLink(Node head) {
Node pre = null;
Node nxt;
while (head != null) {
nxt = head.next;
head.next = pre;
pre = head;
head = nxt;
}
return pre;
}
/*反转双向链表*/
public static Node reverseDualLink(Node head) {
if (head == null) {
return null;
}
Node last = null;
Node next;
while (head != null) {
next = head.next;
head.next = last;
head.prev = next;
last = head;
head = next;
}
return last;
}
/*生成单向链表*/
public static Node generateSingleLink(int[] arr) {
Node head = new Node(arr[0]);
for (int i = 1; i < arr.length; i++) {
addSingleLinkNode(head, arr[i]);
}
return head;
}
/*生成双向链表*/
public static Node generateDualLink(int[] arr) {
Node head = new Node(arr[0]);
for (int i = 1; i < arr.length; i++) {
addDualLinkNode(head, arr[i]);
}
return head;
}
/*添加单链表节点*/
public static void addSingleLinkNode(Node head, int val) {
if (head == null) {
System.out.println("链表头节点为空");
return;
}
if (head.next == null) {
head.next = new Node(val);
return;
}
Node index = head;
while (true) {
if (index.next == null) {
index.next = new Node(val);
return;
} else {
index = index.next;
}
}
}
/*添加双向链表节点*/
public static void addDualLinkNode(Node head, int val) {
if (head == null) {
System.out.println("链表头节点为空");
return;
}
if (head.next == null) {
Node node = new Node(val);
head.next = node;
node.prev = head;
return;
}
Node index = head;
while (true) {
if (index.next == null) {
Node node = new Node(val);
index.next = node;
node.prev = index;
return;
} else {
index = index.next;
}
}
}
/*遍历链表*/
public static void list(Node head) {
if (head == null) {
System.out.println("链表为空");
return;
}
Node index = head;
while (index != null) {
System.out.println(index.val);
index = index.next;
}
}
/*节点*/
private static class Node {
int val;
Node next;
Node prev;
public Node(int val) {
this.val = val;
}
}
}
单链表 双链表: 生成,反转,遍历,删除
于 2022-03-12 14:14:46 首次发布