您的位置:首页 > 编程语言 > Java开发

java实现单向链表CRUD,反转,排序,查找倒数第k个元素,递归输出等操作

2017-08-03 09:41 1251 查看
package myLink;

import javax.xml.transform.Templates;

public class LianBiao {
static Node head=null;
/**
* 查找单链表的中间节点
* */
public Node getMid(){
Node p=head;
Node q=p;
while(p!=null&&p.next!=null&&p.next.next!=null){
p=p.next.next;
q=q.next;
}
return q;
}
/**
* 链表长度
* */
public int getLen(Node head){
int count=0;
Node temp=head;
while(temp!=null){
temp=temp.next;
count++;
}
return count;
}
/**
* 增加节点
* */
public void add(Object obj){
Node n=new Node(obj);
if(head==null){
head=n;
return;
}
Node temp=head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=n;
}
/**
* 遍历链表
* */
public void traver(Node head){
Node temp=head;
while(temp!=null){
System.out.print(temp.obj+"\t");
temp=temp.next;
}
}
/**
* 查找倒数第k个元素
* 思路:p,q先=头节点,p先前进k,p,q再同时前进,返回q
* */
public Node findDSElem(int k){
Node p=head;
Node q=head;
int count=0;
if(k<0||k>getLen(head)){
return null;
}
while(count!=k){
p=p.next;
count++;
}
while(p!=null){
p=p.next;
q=q.next;
}
return q;
}
/**
* 对链表进行排序
* */
public Node orderList(Node n){
Object tmp=null;
Node curNode=head;
Node nextNode=curNode.next;
while(curNode.next!=null){
nextNode=curNode.next;
while(nextNode!=null){
if((int)curNode.obj>(int)nextNode.obj){
tmp=curNode.obj;
curNode.obj=nextNode.obj;
nextNode.obj=tmp;
}
nextNode=nextNode.next;
}
curNode=curNode.next;
}
return head;
}
/**
* 递归遍历
* */
public void printDiGui(Node n){
if(n!=null){
System.out.print(n.obj+"\t");
printDiGui(n.next);
}
}
/**
* 删除重复节点
* */
public void deleteCopy(Node n){
Node cur=head;
while(cur.next!=null){
Node next=cur.next;
if(cur.obj==next.obj){
cur.next=next.next;
cur=cur.next;
}else{
cur=cur.next;
}
}
}
/**
* 删除节点
* */
public void delete(int index){
if(index<1||index>getLen(head)){
return;
}
//头结点,头指针有待完善
if(index==1){
head.next=head.next.next;
return;
}
Node preNode=head;
Node curNode=preNode.next;
int count=1;//count==2
while(curNode!=null){
if(index==count){
preNode.next=curNode.next;
return;
}
preNode=curNode;
curNode=curNode.next;
count++;
}

}
public static void main(String[] args) {
LianBiao lb=new LianBiao();
lb.add(1);
lb.add(3);
lb.add(9);
lb.add(5);
lb.add(4);
lb.add(4);
lb.add(2);
lb.add(6);
/*lb.orderList(head);
lb.traver(head);*/

lb.traver(head);
System.out.println();
//System.out.println(lb.getMid().obj);
//lb.deleteCopy(head);
//System.out.println("长度:"+lb.getLen(head));
//System.out.println(lb.findDSElem(1).obj);
lb.printDiGui(head);
lb.delete(2);
System.out.println();
lb.printDiGui(head);
}
}
class Node{
Object obj;
Node next;
public Node(Object obj){
this.obj=obj;
}
public Node(){

}
/**
* @return the obj
*/
public Object getObj() {
return obj;
}
/**
* @param obj the obj to set
*/
public void setObj(Object obj) {
this.obj = obj;
}
/**
* @return the next
*/
public Node getNext() {
return next;
}
/**
* @param next the next to set
*/
public void setNext(Node next) {
this.next = next;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐