Java 实现链表的反转

mac2022-06-30  84

package List.www.cn;

import java.util.Scanner;

public class ReversP236 { public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.nextLine(); StringBuilder sb=new StringBuilder(s); for(int i=0;i<sb.length();i++) { if(sb.charAt(i)==',') { sb.deleteCharAt(i); } } String str=sb.toString(); in.close(); char[] c=str.toCharArray(); Node1 head=systemIn(c); Node1 head1=head; while(head1!=null) { System.out.print(head1.val+"->"); head1=head1.next; } System.out.println("null"); Node1 temp=revers(head); while(temp!=null) { System.out.print(temp.val+"->"); temp=temp.next; } System.out.println("null"); } public static Node1 systemIn(char[] ch) { if(ch==null||ch.length==0) return null; Node1 head=new Node1('0'); Node1 dummy=head; for(int i=0;i<ch.length;i++) { Node1 cur=new Node1(ch[i]); dummy.next=cur; dummy=dummy.next; } return head.next; } public static Node1 revers(Node1 head) {//反转链表 if(head==null||head.next==null) return head; Node1 dummy=new Node1('0'); dummy.next=head; Node1 cur=head; while(cur.next!=null) { Node1 next=cur.next; cur.next=next.next; next.next=dummy.next; dummy.next=next; } return dummy.next; }

}

转载于:https://www.cnblogs.com/sgbe/p/10717845.html

最新回复(0)