最近刷数据结构,自学的过程绝对还是很有意思的,这里好像才看到程序工作者的智慧。
刷到了链表相关的知识,虽然javayou现成的List可以调用,但是又全都自己实现了一遍,理解内部实现的机制。
关于链表的定义和创建,节点的插入,节点删除,节点查找,判断是否为空,判断是否为尾节点,链表元素的排序,两个有序链表的合并,链表的反转,获取最后四个链表元素,获取链表的中间节点元素,交换链表节点,链表节点元素相加,链表节点元素相乘。这些都做了详细的代码实现。
不多啰嗦了,上代码:
package com.algorithm;
import java.util.ArrayList;
import java.util.Stack;
import com.ListNode.Common;
import com.ListNode.ListNode;
/**
* 链表类的操作
* 包含:
* 链表创建、
* 插入节点、
* 删除节点、
* 查找节点
* 判断是否为空、
* 判断是否为尾、
* 链表排序
* 链表合并、
* 链表反转、
* 获取最后四个、
* 获取中间节点、
* 交换节点
* 链表相加、
* 链表相乘
*/
public class List {
/**
* 链表类
*/
private static class ListNode{
public int element;
public ListNode next;
public ListNode(int element){
this.element = element;
}
}
//测试实例
public static ListNode head = new ListNode( 6 );
private static ListNode second = new ListNode( 1 );
public static ListNode third = new ListNode( 2 );
private static ListNode forth = new ListNode( 5 );
private static ListNode fivth = new ListNode( 4 );
private static ListNode sixth = new ListNode( 3 );
public static ListNode head1 = new ListNode( 0 );
private static ListNode second1 = new ListNode( 6 );
private static ListNode third1 = new ListNode( 7 );
private static ListNode forth1 = new ListNode( 8 );
private static ListNode fivth1 = new ListNode( 9 );
private static ListNode sixth1 = new ListNode( 7 );
public static ListNode head2 = new ListNode( 1 );
public static ListNode second2 = new ListNode( 1 );
private static ListNode third2 = new ListNode( 7 );
public static ListNode forth2 = new ListNode( 8 );
private static ListNode fivth2 = new ListNode( 9 );
private static ListNode sixth2 = new ListNode( 7 );
static {
head.next = second;
second.next = third;
third.next = forth;
forth.next = fivth;
fivth.next = sixth;
head1.next = second1;
second1.next = third1;
third1.next = forth1;
forth1.next = fivth1;
fivth1.next = sixth1;
head2.next = second2;
second2.next = third2;
third2.next = forth2;
forth2.next = fivth2;
fivth2.next = sixth2;
}
/**
* 判断链表是否为空
* @param head 链表头节点
* @return
*/
private boolean isEmpty(ListNode head){
return head.next == null;
}
/**
* 判断是否是尾节点
* @param node 待判断节点
* @return
*/
private boolean isLast(ListNode node){
return node.ne