一.链表题的通用模板
1.首先构造链表
static class ListNode{
public int val;
ListNode next;
ListNode (int x){
val = x;
next = null;
}
}
2.其次初始化链表
private static ListNode initLinkedList(int[] array){
ListNode head = null,cur = null;
for (int i = 0;i < array.length;i ++){
ListNode newNode = new ListNode(array[i]);
newNode.next = null;
if (i == 0){
head = newNode;
cur = head;
}else{
cur.next = newNode;
cur = newNode;
}
}
return head;
}
3.最后写主函数
public static void main(String[] args){
int[] a = {1,2,3,4,5}
ListNode nodeA = initLinkedList(a);
//写包含算法的函数
System.out.println();
}
4.偶尔需要把链表转换为字符串输出
public static String toString(ListNode head){
ListNode current = head;
StringBuilder sb = new StringBuilder();
while (current != null){
sb.append(current.val).append("\t");
current = current.next;
}
return sb.toString();
}
二.常见链表题的算法
1.两个链表第一个公共子节点
public static ListNode findFirstCommonNodeByMap(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null){
return null;
}
ListNode current1 = pHead1;
ListNode current2 = pHead2;
HashMap<ListNode,Integer> hashMap = new HashMap<ListNode,Integer>();
while (current1 != null){
hashMap.put(current1,null);
current1 = current1.next;
}
while (current2 != null){
if (hashMap.containsKey(current2))
return current2;
current2 = current2.next;
}
return null;
2.判断链表是否回文
public static boolean isPalindromeByAllStack(ListNode head){
ListNode temp = head;
Stack<Integer> stack = new Stack();
while (temp != null){
stack.push(temp.val);
temp = temp.next;
}
while (head != null){
if (head.val != stack.pop()){
return false;
}
head = head.next;
}
return true;
}
3.合并有序链表
public static ListNode mergeTwoLists(ListNode list1,ListNode list2){
ListNode newHead = new ListNode(-1);
ListNode res = newHead;
while (list1 != null && list2 !=null){
if (list1.val < list2.val){
newHead.next = list1;
list1 = list1.next;
}else if(list1.val > list2.val){
newHead.next = list2;
list2 = list2.next;
}else{
newHead.next = list2;
list2 = list2.next;
newHead = newHead.next;
newHead.next = list1;
list1 = list1.next;
}
newHead = newHead.next;
}
while (list1 != null){
newHead.next = list1;
list1 = list1.next;
newHead = newHead.next;
}
while (list2 != null){
newHead.next = list2;
list2 = list2.next;
newHead = newHead.next;
}
return res.next;
}
4.寻找倒数第k个结点
public static ListNode getKthFromEnd(ListNode head,int k){
ListNode fast = head;
ListNode slow = head;
while (fast != null && k > 0){
fast = fast.next;
k --;
}
while (fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
5.删除特定结点
public static ListNode removeElements(ListNode head,int val){
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode temp = dummyHead;
while (temp.next != null){
if (temp.next.val == val){
temp.next = temp.next.next;
}else{
temp = temp.next;
}
}
return dummyHead.next;
}