zoukankan      html  css  js  c++  java
  • [Java]链表的打印,反转与删除

    class Node{
    public int value;
    public Node next=null;
    public Node(int value) {
    this.value=value;
    }
    }
    public class LinkedList {
    public static void display(Node head) {
    for(Node cur=head;cur!=null;cur=cur.next) {
    System.out.printf("(%d)->",cur.value);
    }
    System.out.printf("null");
    System.out.printf("%n");
    }
    public static Node pushFront(Node head,int value) {
    Node newnode=new Node(value);
    newnode.next=head;
    return newnode;
    }
    public static Node pushBack(Node head,int value) {
    if(head==null) {
    return pushFront(head,value);
    }else {
    Node newnode=new Node(value);
    Node last=getlast(head);
    last.next=newnode;

    }
    return head;
    }
    public static Node getlast(Node head) {
    Node cur=head;
    while(cur.next!=null) {
    cur=cur.next;
    }
    return cur;
    }
    public static Node reverseList(Node head) {
    Node newList=null;
    Node cur=head;
    while(cur!=null) {
    Node next=cur.next;
    cur.next=newList;
    newList=cur;
    cur=next;
    }
    return newList;
    }
    public static Node removeElements(Node head,int value) {
    Node newlist=null;
    Node cur=head;
    while(cur!=null) {
    Node next=cur.next;
    Node last=null;
    if(cur.value!=value) {
    if(newlist==null) {
    cur.next=newlist;
    newlist=cur ;
    }else {
    last=newlist;
    while(last.next!=null) {
    last=last.next;
    }
    last.next=cur;
    cur.next=null;
    }
    }
    cur=next;
    }
    return newlist;
    }
    public static void main(String[] args) {
    Node head=null;
    head=pushBack(head,1);
    head=pushBack(head,2);
    head=pushBack(head,3);
    display(head);
    head=pushFront(head,10);
    head=pushFront(head,20);
    head=pushFront(head,30);
    display(head);
    head=reverseList(head);
    display(head);
    head=pushBack(head,1);
    display(head);
    head=removeElements(head,1);
    display(head);
    }
    }
    --------------------- 

  • 相关阅读:
    web http协议
    swoole udp
    swoole线程和进程
    SVN中trunk,branches,tags用法详解
    mysql外键使用和事物使用
    xml
    dedecms开启报错
    Django CBV方法装饰器
    Django Cookie和Session
    ORM基础5
  • 原文地址:https://www.cnblogs.com/ly570/p/11001442.html
Copyright © 2011-2022 走看看