• [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);
    }
    }
    --------------------- 

  • 相关阅读:
    《ASP.NET Core项目开发实战入门》带你走进ASP.NET Core开发
    网络监控工具 iftop dstat
    可进行组合的枚举
    查看Qt自带的QSS
    通过文件设置QSS
    QString转QByteArray
    error: jump to case label
    error: static member function cannot have cv-qualifier
    C++ std::vector的大小和容量
    获取QMessageBox返回值
  • 原文地址:https://www.cnblogs.com/ly570/p/11001442.html
Copyright © 2020-2023  润新知