首页 > 代码库 > 链表模板总结

链表模板总结

单链表:

public class ListNode {
  int val;
  ListNode next;
  ListNode (int val) {
    this.val = val;
  }
}

1、反转单链表

技术分享
public void reverseLinkedList(ListNode head) {
  ListNode pre = null;
  while (head != null) {
    ListNode next = head.next;
    head.next = pre;
    pre = head;
    head = next;
  }
  return pre;
}
View Code

 

2、寻找单链表的中点

技术分享
public ListNode findMid(ListNode head) {
  ListNode slow = head;
  ListNode fast = head;
  while (fast != null && fast.next != null) {
    fast = fast.next.next;
    slow = slow.next;
  }
  return slow;
}
View Code

 

链表模板总结