获取单链表节点个数
代码如下:
//方法:获取单链表节点个数(如果带头节点,不需要统计头节点)
public static int getLength(HeroNode head){
if (head.next == null){
return 0;
}
int length = 0;
HeroNode cur = head;
while (cur.next != null){
length++;
cur = cur.next;
}
return length;
}
查找链表中的倒数第k个节点
代码如下:
//编写一个方法,接受head节点,同时接受一个index
//index表示倒数第index个节点
//先把链表从头到尾遍历,得到链表的总长度getLength
//得到size后我们从第一个开始遍历size-index个就可以得到
public static HeroNode findLastIndexNode(HeroNode head, int index){
if (head.next == null){
return null;
}
//第一遍遍历得到链表的长度
int length = getLength(head);
HeroNode temp = head.next;
if (index <= 0 || index > length){
return null;
}
for (int i = 0; i < length - index; i++){
temp = temp.next;
}
return temp;
}
//双指针一遍查找
public static HeroNode findLastIndexNode1(HeroNode head, int index){
if (head.next == null){
return null;
}
HeroNode first = head;
HeroNode second = head;
for (int i = 1; i <= index + 1; i++){
first = first.next;
}
while (first != null){
first = first.next;
second = second.next;
}
return second.next;
}
链表的反转
思路:
1.先定义一个节点reverseHead = new HeroNode();
2.从头到尾遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表最前端
3.原来的链表的head.next = reverseHead.next
代码如下:
//将单链表反转
public static void reverseList(HeroNode head){
//如果当前链表为空或者只有一个节点无需反转
if (head.next == null || head.next.next == null){
return;
}
//定义一个辅助指针(变量),帮助我们遍历原来的链表
HeroNode cur = head.next;
HeroNode next = null;//指向当前节点(cur)的下一个节点
HeroNode reverseHead = new HeroNode(0,"","");
//遍历原来链表。没遍历一个节点,就将其取出,并放在新链表reverseHead的最前端
while (cur != null){
next = cur.next;//先暂时保存当前节点的下一个节点
cur.next = reverseHead.next;//将cur的下一个节点指向新链表的最前端
reverseHead.next = cur;//将cur接在新链表上
cur = next;//让cur后移
}
//将head.next指向reverseHead.next实现单链表的反转
head.next = reverseHead.next;
}
逆序打印单链表
方法一:先将单链表进行反转操作,然后在遍历即可,这样的做的问题就是会破坏单链表的结构,不建议。
方法二:可以利用栈这个数据结构,将各个节点压入栈中,然后利用栈的先进先出特点,就实现了逆序打印的功能。
代码如下:
//方法二:可以利用栈这个数据结构,将各个节点压入栈中,然后利用栈的先进先出特点,就实现了逆序打印的功能
public static void reversePrint(HeroNode head){
if (head.next == null){
System.out.println("空链表!!");
}
HeroNode cur = head.next;
Stack<HeroNode> stack = new Stack<HeroNode>();
while (cur != null){
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0){
System.out.println(stack.pop());
}
}
合并两个有序的单链表:
代码如下:
public static void mergeList(HeroNode head1, HeroNode head2){
HeroNode cur = head1.next;
HeroNode cur1 = head2.next;
HeroNode newHerNOde = new HeroNode(0," "," ");
HeroNode temp = newHerNOde;
while (cur != null && cur1 != null){
if (cur.no < cur1.no){
temp.next = cur;
cur = cur.next;
}else {
temp.next = cur1;
cur1 = cur1.next;
}
temp = temp.next;
}
temp.next = cur == null ? cur1 : cur;
}
ps:源码自取,点击即可
ps:以上笔记均来自尚硅谷韩顺平老师《Java数据结构与java算法》