package com.ys;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class MyLinkedList {
Node head=null;
public void add(int data){
Node node =new Node(data);
if (head==null){
head=node;
}
Node demo=head;
while (demo.next!=null){
demo=demo.next;
// System.out.println(demo);
}
demo.next=node;
}
/**
* 获取链表的长度
* @return
*/
public int getLength(){
int a=0;
Node demo=head;
while (demo==null){
a++;
demo=demo.next;
}
return a;
}
public boolean deleteNode(int index){
if (index<1||index>getLength()){
return false;
}
if (index==1){
head=head.next;
}
int i=2;
Node node=head;
while (index!=i){
node=node.next;
i++;
}
node.next=node.next.next;
return true;
}
public void printNodeData(){
Node node=head;
while (node!=null)
{
System.out.println(node.data);
node=node.next;
}
}
/**
* 删除链表中重复的数据
* @param head
*/
public void deleteDuplecate(Node head){
Node tem=head;
Node pre=null;
HashMap<Integer,Integer>table=new HashMap<Integer, Integer>();
while (tem!=null){
if (table.containsKey(tem.data)){
pre.next=tem.next;
}else {
table.put(tem.data,1);
pre=tem;
}
tem=tem.next;
}
}
/**
* 对链表进行排序
*/
public void sortNode(){
Node curNode=head;
Node nextNode;
int temp;
while (curNode.next!=null){
nextNode=curNode.next;
while (curNode.next!=null){
if(curNode.data>nextNode.data){
temp=nextNode.data;
nextNode.data=curNode.data;
curNode.data=temp;
}
nextNode=nextNode.next;
}
curNode=curNode.next;
}
}
/**如何找出单链表中的倒数第k个元素
*
*/
public Node findElem(Node head,int k){
Node p1=head;
Node p2=head;
if (p1==null)return null;
for (int i = 0; i <k-1&&p1!=null ; i++) {
p1=p1.next;
}
if (p1==null){
System.out.println("k不合法");
}
while (p1!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
/**
* 从尾到头打印单链表
* @param printNode
*/
public void printListFromEndToHead(Node printNode){
if (printNode!=null){
printListFromEndToHead(printNode.next);
System.out.println(printNode.data);
}
}
/**
* 打印中间节点
* @param head
* @return
*/
public Node searchMiddle(Node head){
Node p1=head;
Node p2=head;
while (p1!=null&&p2!=null&&p1.next!=null&&p2.next.next!=null){
p1=p1.next;
p2=p2.next;
}
return p1;
}
/**
* 检测一个链表是否有环
* @return
*/
public boolean IsLoop(){
Node fast=head;
Node slow=head;
if (fast==null)return false;
while (fast!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return !(fast==null);
}
/**
* 如何判断两个链表是否相交
* 相同的尾节点即相交
*/
public boolean isIntersect(Node h1,Node h2){
if (h1==null||h2==null){
return false;
}
while (h1.next!=null){
h1=h1.next;
}
while (h2.next!=null){
h2=h2.next;
}
return h1==h2;
}
public static void main(String[] args) {
MyLinkedList myLinkedList=new MyLinkedList();
List list=new LinkedList();
System.out.println(333);
myLinkedList.add(7);
System.out.println(myLinkedList.getLength());
myLinkedList.deleteNode(1);
System.out.println(myLinkedList.getLength());
myLinkedList.add(3);
myLinkedList.add(2);
myLinkedList.printNodeData();
}
}