1. 单链表的逆置
思路:通过头插节点来完成单链表的逆置,定义一个cur指向head的下一个节点,curNext记录cur的next节点,
- 当链表为空,即头节点head为空时,返回null。
- 当链表只有一个head节点时,返回head。
- 头插cur节点,先让cur指向head的next节点,然后把head.next设为空,因为逆置之后head.next就为尾节点,其next为null;开始头插节点,当cur不为null时,一直进行头插,让curNext记录cur的next节点,然后让cur的next指向head,再让头插的cur节点成为新的head,接着cur往下走。
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
if(head.next == null) {
return head;
}
ListNode cur = head.next;
head.next = null;
while(cur != null) {
ListNode curNext = cur.next;
cur.next = head;
head = cur;
cur = curNext;
}
return head;
}
2. 获取链表中间节点
思路:指针法,定义两个指针fast和slow,fast一次走两步,slow一次走一步,当fast为空或fast.next为空时,slow即为中间节点
public ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
3. 获取倒数第k个节点
思路:定义两个指针fast和slow,再定义一个计数器count,先让fast走k-1步,然后同时和slow走到fast.next为null时,即slow为第k节点
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null) {
return null;
}
if(k <= 0) {
return null;
}
ListNode fast = head;
ListNode slow = head;
int count = 0;
while(count != k-1) {
if(fast.next != null){
fast = fast.next;
count++;
}else {
return null;
}
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
4. 合并两个有序链表
思路:定义一个新的头节点newH,tmpH,通过tmpH来遍历串联两个链表,然后比较两个链表的头节点,谁小就让谁指向tmpH的next节点,两个head往下走,一直到两个链表的head为空结束。
public static ListNode mergeTwoLists(ListNode headA,ListNode headB) {
//实例化 静态内部类对象
ListNode newHead = new MySingleList.ListNode(-1);
ListNode tmp = newHead;
//保证两个链表都有数据
while(headA != null && headB != null) {
if(headA.val < headB.val) {
tmp.next = headA;
headA = headA.next;
tmp = tmp.next;
}else {
tmp.next = headB;
headB = headB.next;
tmp = tmp.next;
}
}
if(headA != null) {
tmp.next = headA;
}
if(headB != null) {
tmp.next = headB;
}
return newHead.next;
}