标题单链表面试题:
public int getLength(HeroNode head){
HeroNode temp = head;
int length = 0;
while(temp.next != null){
length++;
temp = temp.next;
}
return length;
}
- 查找单链表中倒数第k个节点:
把链表从头到尾遍历一遍,获取链表总长度len;
再遍历一遍,第len-k+1个节点就是所需节点
public HeroNode findLastNode(HeroNode head, int k){
if(head.next == null) return null;
int len = getLength(head);
if(k < 0 || k > len) return null;
int count = 0;
HeroNode temp = head;
while(temp.next != null){
count++;
temp = temp.next;
if(count == len - k + 1) break;
}
return temp;
}
- 单链表的反转:
遍历链表,将节点重新插入到头节点的后面。
public void reverseLinkedList(HeroNode head){
if(head.next == null || head.next.next == null) return ;
HeroNode cur = head.next;
HeroNode next = null;
head.next = null;
while(cur != null){
next = cur.next;
cur.next = head.next;
head.next = cur;
cur = next;
}
}
- 逆序打印单链表
思路1:先将单链表进行反转操作,然后再遍历即可。这样做的问题是会破坏原来的单链表的结构,不建议
思路2:利用栈这个数据结构,将各个数据节点压入栈中,然后利用栈的先进先出的特点来实现逆序打印
public void printFromLast(HeroNode head){
if(head.next == null) return ;
Stack<HeroNode> stack = new Stack<HeroNode>();
HeroNode cur = head.next;
while(cur != null){
stack.push(cur);
cur = cur.next;
}
while(stack.size() > 0){
System.out.println(stack.pop());
}
}
public HeroNode merge(HeroNode head1, HeroNode head2){
HeroNode result = head1;
if(head2.next == null) return result;
HeroNode cur = head2.next;
HeroNode next = null;
while(cur != null){
next = cur.next;
HeroNode temp = result;
while(temp.next != null && cur.no > temp.next.no){
temp = temp.next;
}
if(temp.next != null && temp.next.no == cur.no){
System.out.println("编号重复了哦~");
}else{
cur.next = temp.next;
temp.next = cur;
}
cur = next;
}
return result;
}