题目描述
解题方法1
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
reverse(head);
for(Node p = head.next;p!=null;p=p.next){
System.out.println(p.val);
}
}
//反转链表
public static Node reverse(Node head){
if(head==null || head.next==null){
return head;
}
Node p = head.next;
head.next = null;
while(p!=null){
Node temp = p.next;
p.next = head.next;
head.next = p;
p=temp;
}
return head;
}
public static Node create(int[] arr){
Node head = new Node(0); //头节点
Node newnode = null; //指向新节点
Node tail = head; //指向链表尾节点
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
zuiziyoudexiao
发布了99 篇原创文章 · 获赞 61 · 访问量 17万+
私信
关注