单链表反转
链表中环的检测
两个有序的链表合并
删除链表倒数第 n 个结点
求链表的中间结点
一、单链表反转
1.1、单链表反转——递归法
参考资料:leetcode 206 号算法题:反转单链表【数据结构与算法】
public class PeopleTest {
public static void main(String[] args) {
Node head = new Node(2);
Node node1 = new Node(3);
Node node2 = new Node(1);
Node node3 = new Node(4);
head.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
// 打印反转前的链表
Node h = head;
while (null != h) {
System.out.print(h.getData() + " ");
h = h.getNext();
}
// 递归调用反转方法
// head = reverseListNode(head);
//遍历调用反转方法
head = reverseList(head);
System.out.println("=============");
Node h2 = head;
while (null !=h2){
System.out.print(h2.getData()+" ");
h2 = h2.getNext();
}
// People p = new People();
// p.setAge(12);
// p.setName("zhangsan");
//
// //对象转字符串
// System.out.println("对象转字符串。。。。。");
// JSONObject jsonObject = JSONObject.fromObject(p);
// //【这里调用的不是People的toString方法】
// String s = jsonObject.toString();
// System.out.println("JSON对象:"+s);
//
// JSONArray jsonArray = JSONArray.fromObject(p);
// String s1 = jsonArray.toString();
// System.out.println("JSON集合:"+s1);
//
//
// //字符串转对象
// System.out.println("字符串转对象。。。。。");
// JSONObject jsonObject1 = JSONObject.fromObject(s);
// People o1 = (People) JSONObject.toBean(jsonObject1, People.class);
// System.out.println("json字符串对象转对象:"+o1);
//
// JSONArray jsonArray1 = JSONArray.fromObject(s1);
// Object o2 = jsonArray1.get(0);
// JSONObject jsonObject3 = JSONObject.fromObject(o2);
// People o3 = (People) JSONObject.toBean(jsonObject3, People.class);
// System.out.println("json字符串集合转对象:"+o3);
}
public static Node reverseListNode(Node head){
// head看作是前一结点,head.getNext()是当前结点,reHead是反转后新链表的头结点
if (head == null || head.getNext() == null) {
return head;// 若为空链或者当前结点在尾结点,则直接还回
}
Node reHead = reverseListNode(head.getNext());// 先反转后续节点head.getNext()
head.getNext().setNext(head);// 将当前结点的指针域指向前一结点
head.setNext(null);// 前一结点的指针域令为null;
return reHead;// 反转后新链表的头结点
}
}
1.2、工具类——结点类
public class Node {
private Object data;//数据域
private Node next;//指针域
public Node(Object data){
this.data = data;
}
public Node(Object data,Node next){
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
1.3、单链表反转——遍历法
//如何实现链表的反转
public static Node reverseList(Node head){
//单链表为空或只有一个节点,直接返回原单链表
if (head == null || head.getNext() == null){
return head;
}
//前一个节点指针
Node preNode = null;
//当前节点指针
Node curNode = head;
//下一个节点指针
Node nextNode = null;
//以下这一步为什么自己写的这样?
// while (cur.getNext() != null) {======================
while (curNode != null){
nextNode = curNode.getNext();//nextNode 指向下一个节点
curNode.setNext(preNode);//将当前节点next域指向前一个节点
preNode = curNode;//preNode 指针向后移动
curNode = nextNode;//curNode指针向后移动
}
//这里为什么是前置结点?========================
return preNode;
}