本期我们就主要单链表中其它类型的题目进行分析
表解体经典思路解法
本期我们讲解的链表面试题其他类型使用的技巧。
经典面试题:对链表进行排序
给一个链表,将链表从小到大的顺序排列。相关代码如果下:
public Node orderList() {
Node nextNode = null;
int tmp = 0;
Node curNode = head;
while (curNode.next != null) {
nextNode = curNode.next;
while (nextNode != null) {
if (curNode.data > nextNode.data) {
tmp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = tmp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
思路:这种排序的思路如同冒泡排序,使用内外两层循环,内部循环每次将此次循环的最小数据放在最开头,外部循环每次前进一步,直到最终排序完成。
经典面试题:删除链表中的重复节点
删除链表中存在的重复数据库,这里我们直接上代码。
public void deleteDuplecate(Node head) {
Node p = head;
while (p != null) {
Node q = p;
while (q.next != null) {
if (p.data == q.next.data) {
q.next = q.next.next;
} else
q = q.next;
}
p = p.next;
}
}
思路:这里我们通过内外两层循环,外部循环每次向外部推动一步,内部循环每次去查看省下的数据是否与最开始的数据相同,如果相同的话就将数据删除。直到最终循环结束,此时就将相同的数据删除了。
经典面试题:从尾到头输出单链表,采用递归方式实现
通过递归的方式将链表从结尾的数据到头的数据进行打印。
public void printListReversely(Node pListHead) {
if (pListHead != null) {
printListReversely(pListHead.next);
System.out.println("printListReversely:" + pListHead.data);
}
}
思路:这个题目让我们对递归的算法进一步熟悉,当层层深入的时候,最终到达链表的最后一个节点,此时将此节点的数据打印出来,这个时候开始最后第二层方法,此时打印倒数第二个数据,最终数据被从结尾到开头依次被打印出来。
经典面试题:回文链表
判断一个链表是否是回文链表
public boolean isPalindrome(ListNode head) {
ListNode reverseNode = null;
ListNode nomalNode;
if (head.next.next == null) {
reverseNode = head;
nomalNode = head.next;
reverseNode.next = null;
} else {
ListNode slow = head;
ListNode fast = head;
ListNode tempSlow;
ListNode tempFast;
//通过快慢指针找中间值,顺便反转前半截链表
while (fast.next != null && fast.next.next != null) {
tempSlow = slow.next;
tempFast = fast.next.next;
slow.next = reverseNode;
reverseNode = slow;
slow = tempSlow;
fast = tempFast;
}
tempSlow = slow.next;
slow.next = reverseNode;
reverseNode = slow;
//考虑链表是奇数长度链表
if (fast.next == null) {
reverseNode = reverseNode.next;
}
nomalNode = tempSlow;
}
//遍历后半截找不同
while (nomalNode != null && reverseNode != null) {
if (nomalNode.data != reverseNode.data) {
return false;
}
nomalNode = nomalNode.next;
reverseNode = reverseNode.next;
}
return true;
思路:首先我们通过快慢指针找中间值,同时顺便反转前半截链表,然后将翻转的前半段链表与遍历后半截找是否不同,最终可以判断是否是回文链表。
参考:
https://www.cnblogs.com/llfy/p/9395936.html