链表
小结上图:
- 链表是以节点的方式来存储, 是链式存储
- 每个节点包含 data 域, next 域:指向下一个节点.
- 如图:发现 链表的各个节点不一定是连续存储.
- 链表分 带头节点的链表和 没有头节点的链表,根据实际的需求来确定
单链表
单链表看似连续 但是并不是 这只是逻辑结构
不考虑排名
过程:
添加(创建)
1.先创建一个head头节点,作用就是表示单链表的头2.后面我们每添加一个节点,就直接加入到链表的最后遍历:
3.通过一个辅助变量,帮助遍历整个链表
//小的知识点:
1.在多重while嵌套结构中使用break,会退出距离break最近的那一层while循环,且多从if嵌套对break无约束作用,会跳出最外层if,寻找与之最近的最内层while跳出。
2.Java中虽然没有指针但是有引用
3.在单链表的实现中, 我们经常会写一个Node类作为内部类供LinkedList(链表类)使用,其中有一个Node类的变量 next 用于存储下一个结点的位置(即 next 持有着到下一个结点的引用). 所以我们可以通过temp = temp.next; 来移动到下一个结点.
如下面的代码中,HeroNode类中的HeroNode next; 这里的HeroNode next;的next就用与存储下一个节点的位置,我们通过链表类SingleLinkedList来对节点进行操作;
在单链表中我们通常使用一个固定的节点头来方便我们的操作private HeroNode head = new HeroNode(0,"","");
HeroNode temp = head;//定义一个辅助节点,用来指向当前的头节点
通过temp.next == null来判断是否有下一个节点
temp = temp.next;来对节点进行移动
不考虑排名代码:
package com.iswhl.linkedlist;
public class SingleLinkedListDemo {
public static void main(String[] args) {
//测试
// 先创建节点
HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨");
HeroNode heroNode2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode heroNode3 = new HeroNode(3, "吴用", "智多星");
HeroNode heroNode4 = new HeroNode(4, "林冲", "豹子头");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.add(heroNode1);
singleLinkedList.add(heroNode2);
singleLinkedList.add(heroNode3);
singleLinkedList.add(heroNode4);
//遍历链表
singleLinkedList.list();
}
}
//链表
class SingleLinkedList{
//初始化头节点
private HeroNode head = new HeroNode(0,"","");
//思路:
//1.找当前链表中的最后一个节点
//2.将该最后一个节点的下一个,指向新的节点,从而实现,新节点的添加
//
//添加到列表中
public void add(HeroNode heroNode){
HeroNode temp = head;//定义一个辅助节点,用来指向当前的头节点
while (true){
//判断当前节点是否有下一个节点,即是否为最后一个节点
//如果是的则结束循环
if (temp.next == null){
break;
}
//如果不是则找到,当前节点的下一个节点
temp = temp.next;
}
//此时temp为当前链表的最后的位置
//这时添加给当前链表,添加新的节点时,即将当前的最后节点的下一个指针指向到新加的节点上
temp.next = heroNode;
}
//遍历链表
public void list(){
//判断链表是否为空
if (head.next == null){
System.out.println("当前链表为空");
}
//因为头节点,不使用所以应该从头节点的下一个节点开始遍历
HeroNode temp = head.next;
while (true){
//判断当前链表是否为空,若非空则输出
if (temp == null){
break;
}
//输出当前的节点
System.out.println(temp);
//输出后将当前节点后移
temp = temp.next;
}
}
}
//节点
class HeroNode{
private int no;
private String name;
private String nickname;
HeroNode next;
//构造函数
public HeroNode(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
//为了方便显示,这里重写了toString方法
@Override
public String toString() {
return "{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
考虑排名
思路:
需要按照编号的顺序添加
1.首先找到新添加的节点的位置,是通过辅助变量(指针),通过遍历来搞定2.新的节点.next =temp.next
3.将temp.next=新的节点
考虑排名代码
package com.iswhl.linkedlist;
public class SingleLinkedListDemo {
public static void main(String[] args) {
//测试
// 先创建节点
HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨");
HeroNode heroNode2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode heroNode3 = new HeroNode(3, "吴用", "智多星");
HeroNode heroNode4 = new HeroNode(4, "林冲", "豹子头");
SingleLinkedList singleLinkedList = new SingleLinkedList();
// singleLinkedList.add(heroNode1);
// singleLinkedList.add(heroNode2);
// singleLinkedList.add(heroNode3);
// singleLinkedList.add(heroNode4);
singleLinkedList.addByOrder(heroNode4);
singleLinkedList.addByOrder(heroNode3);
singleLinkedList.addByOrder(heroNode1);
singleLinkedList.addByOrder(heroNode2);
//遍历链表
singleLinkedList.list();
HeroNode heroNode5 = new HeroNode(3, "吴~", "智多星~");
singleLinkedList.update(heroNode5);
System.out.println("更新后的");
singleLinkedList.list();
singleLinkedList.delete(4);
singleLinkedList.delete(1);
System.out.println("删除后的");
singleLinkedList.list();
int statistics = Statistics(singleLinkedList.getHead());
System.out.println("可用元素有"+statistics+"个");
}
//求单链表中有效节点的个数的方法---(如果有头节点则头节点不计算在里面)
public static int Statistics(HeroNode head){
HeroNode temp = head.next;
int length = 0;
while (true){
if (temp.next != null){
length++;
}
if (temp.next == null){
length++;
break;
}
temp = temp.next;
}
return length;
}
}
//链表
class SingleLinkedList{
public HeroNode getHead() {
return head;
}
public void setHead(HeroNode head) {
this.head = head;
}
//初始化头节点
private HeroNode head = new HeroNode(0,"","");
//思路:
//1.找当前链表中的最后一个节点
//2.将该最后一个节点的下一个,指向新的节点,从而实现,新节点的添加
//
//添加到链表中
public void add(HeroNode heroNode){
HeroNode temp = head;//定义一个辅助节点,用来指向当前的头节点
while (true){
//判断当前节点是否有下一个节点,即是否为最后一个节点
//如果是的则结束循环
if (temp.next == null){
break;
}
//如果不是则找到,当前节点的下一个节点
temp = temp.next;
}
//此时temp为当前链表的最后的位置
//这时添加给当前链表,添加新的节点时,即将当前的最后节点的下一个指针指向到新加的节点上
temp.next = heroNode;
}
//排序添加到链表中
public void addByOrder(HeroNode heroNode){
HeroNode temp = head;
boolean flag = false;
while (true){
//判断是否为最后一个节点
if (temp.next == null){
break;
}
//找到节点的no大于,要插入节点的位置,找到其前一个的位置
if(temp.next.no > heroNode.no){
break;
//判断是否相等,若相等则不允许插入
}else if(temp.next.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;//链表后移
}
if (flag){
System.out.println("已有相同的值了,不能添加");
}else {
//插入过程
heroNode.next = temp.next;
temp.next = heroNode;
}
}
//修改节点
public void update(HeroNode heroNode){
HeroNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.no == heroNode.no){
//表示找到了该节点
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = heroNode.name;
temp.nickname = heroNode.nickname;
}
}
//删除节点节点
// 从单链表中删除一个节点的思路
//1.我们先找到需要删除的这个节点的前一个节点temp2. temp.next =temp.next.next
//3.被删除的节点,将不会有其它引用指向,会被垃圾回牧机制回收
public void delete(int i){
HeroNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.no == i){
//表示找到了该节点
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.next = temp.next.next;
}
}
//遍历链表
public void list(){
//判断链表是否为空
if (head.next == null){
System.out.println("当前链表为空");
}
//因为头节点,不使用所以应该从头节点的下一个节点开始遍历
HeroNode temp = head.next;
while (true){
//判断当前链表是否为空,若非空则输出
if (temp == null){
break;
}
//输出当前的节点
System.out.println(temp);
//输出后将当前节点后移
temp = temp.next;
}
}
}
//节点
class HeroNode{
public int no;
public String name;
public String nickname;
HeroNode next;
//构造函数
public HeroNode(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
//为了方便显示,这里重写了toString方法
@Override
public String toString() {
return "{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
面试题:
单链表的常见面试题有如下:
1)求单链表中有效节点的个数
int statistics = Statistics(singleLinkedList.getHead());
System.out.println("可用元素有"+statistics+"个");
//求单链表中有效节点的个数的方法---(如果有头节点则头节点不计算在里面)
public static int Statistics(HeroNode head){
HeroNode temp = head.next;
int length = 0;
while (true){
if (temp.next != null){
length++;
}
if (temp.next == null){
length++;
break;
}
temp = temp.next;
}
return length;
}
2)查找单链表中的倒数第k个结点【新浪面试题】
思路
1。编写一个方法,接收head节点,同时接收一个index2. index表示是倒数第index个节点
3。先把链表从头到尾遍历,得到链表的总的长度getLength
4。得到size 后,我们从链表的第一个开始遍历(size-index)个,就可以得到
//方法1
public static HeroNode findLastNode(HeroNode head, int index) {
HeroNode temp = head.next;
int statistics = Statistics(head);
int i = statistics - index;
int p = 0;
while (true) {
if (temp.next == null || i == p) {
break;
}
temp = temp.next;
p++;
}
return temp;
}
//方法2
public HeroNode findNodeStartLast(HeroNode head ,int index){
// 如果链表为空 返回null
if (head.next == null){
return null;
}
// 变历得到链表的长度
int length = this.getLength(head);
// 再一次遍历 返回 第length - index
// 先做一个index的校验
if(index <= 0 || index > length){
return null;
}
// 定义一个辅助节点
HeroNode temp = head.next;
for(int i = 0 ;i < length-index ;i++ ){
temp = temp.next;
}
return temp;
}
3)单链表的反转【腾讯面试题】
思路:
1.先定义一个节点reverseHead =new HeroNode();
2.从头到尾遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表reverseHead的最前端.
3.原来的链表的head.next =reverseHead.next
注:reversalHead.next 即为头节点的下一个,即链表的第一个节点
public static void reversalNode(HeroNode head){
//判断当前单链表中,是否为空或只有一个节点
if (head.next == null || head.next.next == null){
return ;
}
//定义一个当前前节点
HeroNode cur = head.next;//记录当前节点
HeroNode next = null;//定义一个空节点
HeroNode reversalHead = new HeroNode(0, "", "");
while (cur != null){
next = cur.next;//记录当前节点的下一个节点
//(reversalHead.next)即为头节点的下一个,即链表的第一个节点
cur.next = reversalHead.next;//将cur的下一个节点指向新节点的最前端,
//(reversalHead.next)即为头节点的下一个,即链表的第一个节点
reversalHead.next = cur;//让头节点的下一个指向这个新加的节点
cur = next;//当前节点下移
}
head.next = reversalHead.next;
}
4)从尾到头打印单链表【百度,要求方式1:反向遍历。方式2:Stack栈】
思路
1.上面的题的要求就是逆序打印单链表.
2.方式1:先将单链表进行反转操作,然后再遍历即可,这样的做的问题是会破坏原来的单链表的结构,不建议
3.方式2:可以利用找这个数据结构,将各个节点压入到栈中,然后利用栈的先进后出的特点,就实现了逆序打印的效果.
举例演示栈的使用stack
5)合并两个有序的单链表,合并之后的链表依然有序【课后练习.】
//将两个有序的链表合并为一个有序的链表
public static HeroNode mergeTwoList(HeroNode head1, HeroNode head2) {
if(head1 == null){
return head1;
}
if(head2 == null){
return head2;
}
HeroNode newNode = null;
HeroNode last = null;
HeroNode cur1 = head1;
HeroNode cur2 = head2;
while(cur1 != null && cur2 != null){
if(cur1.no < cur2.no){
HeroNode next = cur1.next;
if(newNode == null){
//头插
cur1.next = newNode;
newNode = cur1;
}else{
last.next = cur1;
}
//保证last永远指向最后一个结点
last = cur1;
cur1 = next;
}else{
HeroNode next = cur2.next;
if(newNode == null){
cur2.next = newNode;
newNode = cur2;
}else{
last.next = cur2;
}
last = cur2;
cur2 = next;
}
}
if(cur1 != null){
last.next = cur1;
}else{
last.next = cur2;
}
return newNode;
}
运用的知识点
Java Stack 类
栈是Vector的一个子类,它实现了一个标准的后进先出的栈。
堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。
Stack()
除了由Vector定义的所有方法,自己也定义了一些方法:
序号 | 方法描述 |
---|---|
1 | boolean empty() 测试堆栈是否为空。 |
2 | Object peek( ) 查看堆栈顶部的对象,但不从堆栈中移除它。 |
3 | Object pop( ) 移除堆栈顶部的对象,并作为此函数的值返回该对象。 |
4 | Object push(Object element) 把项压入堆栈顶部。 |
5 | int search(Object element) 返回对象在堆栈中的位置,以 1 为基数。 |
import java.util.*;
public class StackDemo {
static void showpush(Stack<Integer> st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack<Integer> st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack<Integer> st = new Stack<Integer>();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
以上实例编译运行结果如下:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
package com.iswhl.linkedlist;
import java.util.Stack;
public class TestStack {
public static void main(String[] args) {
Stack<String> strings = new Stack<>();
//入栈
strings.push("a");
strings.push("b");
strings.push("c");
strings.add("a");
strings.add("b");
strings.add("c");
//出栈
while (strings.size()>0){
System.out.println(strings.pop());
}
}
}
运行结果:
c
b
a
c
b
a
关于Java 中stack()类中的add()方法与push()的区别
//对于add方法
/*Appends the specified element to the end of this Vector.*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
//对于push方法
/*Pushes an item onto the top of this stack. This has exactly the same effect as:
addElement(item)*/
public E push(E item) {
addElement(item);
return item;
}
/*Adds the specified component to the end of this vector, increasing its size by one. */
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
通过stack类add方法和push方法源代码可知, add方法其实调用的是Vector类的add方法,返回的是一个boolean类型的值,而push方法则是Stack类在Vector类的addElement方法基础上进修了一些修改,返回当前添加的元素。
/Pushes an item onto the top of this stack. This has exactly the same effect as:
addElement(item)/
public E push(E item) {
addElement(item);
return item;
}
/*Adds the specified component to the end of this vector, increasing its size by one. */
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
通过[stack类](https://so.csdn.net/so/search?q=stack类&spm=1001.2101.3001.7020)**add方法**和**push方法**源代码可知, **add方法**其实调用的是[Vector](https://so.csdn.net/so/search?q=Vector&spm=1001.2101.3001.7020)类的add方法,返回的是一个boolean类型的值,而**push方法**则是Stack类在Vector类的addElement方法基础上进修了一些修改,返回当前添加的元素。