题目1:
单链表(有头结点)的反转
代码:
思路:从头到尾遍历原链表,每遍历一个节点,就将其取出,并用头插法插在新链表上,最后再拼上头结点
public static void reversetList(HeroNode head) {
// 当链表为空/只有一个时,不需反转
if (head.next == null || head.next.next == null) {
return;
}
// 定义一个辅助指针,遍历原链表
HeroNode cur = head.next;
// 用于动态指向 当前节点【cur】的 下一个节点
HeroNode next = null;
// 新链表的头结点
// public HeroNode(int no, String name, String nickname){}
HeroNode reversetHead = new HeroNode(0, "", "");
while (cur != null) {
next = cur.next;
cur.next = reversetHead.next;
reversetHead.next = cur;
cur = next;
}
// 将head.next 指向 reverseHead.next , 实现单链表的反转
head.next = reversetHead.next;
}
题目2:
从尾到头打印单链表(有头结点)
代码:
思路1:先将单链表进行反转操作,然后再遍历即可 【会破坏原单链表的结构,不推荐】
思路2:利用栈的先进后出,将各个节点压入栈中再打印出栈
public static void reversetPrint(HeroNode head) {
// 判空
if(head.next == null)
return;
// 创建一个栈
Stack<HeroNode> stack = new Stack();
HeroNode temp = head.next;
// 将链表所有节点入栈
while (temp != null) {
stack.push(temp); // 节点 入栈
temp = temp.next; // 节点后移
}
// 所有节点依次打印出栈
while(stack.size() >0) {
System.out.println(stack.pop());
}
}
题目3:
合并两个有序的单链表(有头结点),合并之后的链表依然有序
代码:
思路1:两个有序链表1和2,视1为主链,遍历2中的元素并插入1中
public static void twoLinkedList(Node head1, Node head2) {
// 如果两个链表均为空,则无需合并,直接返回
if((head1.next == null && head2.next == null) || head2.next == null) {
return;
}
// 如果其中head2为空
else if(head1.next == null) {
head1.next = head2.next;
}
else{
Node cur2 = head2.next;
Node cur1 = head1.next;
Node next2 = null;
while(cur2 != null){
while(cur2.no <= cur1.next.no) {
next2 = cur2.next;
cur2.next = cur1.next;
cur1.next = cur2;
cur2 = next2;
}
cur1 = cur1.next;
if(cur1.next == null) {
cur1.next = cur2;
break;
}
}
}
}
思路2: 新建链表3,分别比较1和2中的元素,不断插入最小结点直至1和2结点耗尽