单链表翻转and删除指定元素
/**
* 链表反转
*/
public class Day_2 {
public static void main(String[] args) {
LinkNode n1 = new LinkNode(1, new LinkNode(3, new LinkNode(5, new LinkNode(7))));
LinkNode newLinkedList = reseverLinkList(n1);
while (newLinkedList != null) {
System.out.print(newLinkedList.value + " ");
newLinkedList = newLinkedList.next;
}
}
/*
反转链表
*/
private static LinkNode reseverLinkList(LinkNode n1) {
// 如果n1为空,则直接返回pre pre是空
// if(n1 == null || n1.next == null) {
// return n1;
// }
LinkNode next = null, pre = null;
while (n1 != null) {
//获取到下一个节点
next = n1.next;
//将当前节点指向上一个节点节点
n1.next = pre;
// 将自己存储为上一个节点,
pre = n1;
// 指针进入下一个节点
n1 = next;
}
return pre;
}
/*
删除链表的指定值
*/
public static LinkNode delLinkedListNode(LinkNode n1, int num) {
//先看看头部是否是需要被删除的元素,如果是的话,找到新的头部
while (n1 != null) {
if (n1.value != num) {
break;
}
n1 = n1.next;
}
LinkNode pre = n1;
LinkNode cur = n1;
while (cur != null) {
if (cur.value == num) {
pre.next = cur.next;
} else {
pre = cur;
}
}
return n1;
}
}
class LinkNode {
int value;
LinkNode next;
public LinkNode() {
}
public LinkNode(int val) {
this.value = val;
}
public LinkNode(int val, LinkNode next) {
this.value = val;
this.next = next;
}
}
单链表实现栈内存模拟
public class MyStack {
public static void main(String[] args) {
LinkedList l1 = new LinkedList();
l1.addNode(new ListNode(1));
l1.addNode(new ListNode(3));
ListNode head = l1.addNode(new ListNode(5));
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
/**
* 单向链表结构
*/
class LinkedList {
// 从头部删除,从尾部删除
// 头部节点
private ListNode head;
// 尾部节点
private ListNode tail;
/**
* 添加新节点至头部
* @param node
* @return 新头部
*/
public ListNode addHeadNode(ListNode node) {
if (head == null) {
head = node;
tail = node;
} else {
ListNode tempNode = head;
head = node;
head.next = tempNode;
}
return head;
}
/**
* 添加节点至结尾
* @param node
* @return 链表头部
*/
public ListNode addNode(ListNode node) {
if (head == null) {
head = node;
} else {
tail.next = node;
}
tail = node;
return head;
}
/**
* 删除头部链表节点
* @return 新的头部节点
*/
public ListNode delHeadNode(){
// 如果head的下一个为空,说明只有一个节点,返回空即可;
if(head.next == null){
head = null;
tail = null;
}else{
head = head.next;
}
return head;
}
public ListNode delNode(){
return null;
}
}
/**
* 双向链表结构
*/
class doubleLinkedList {
}
/**
* 链表节点
*/
class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
双链表还没开始做~
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容