一、反转单链表
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode Rehead=null;
while(head!=null)
{
ListNode tmp=head;
head=head.next;
tmp.next=Rehead;
Rehead=tmp;
}
return Rehead;
}
public void PrintList(ListNode head){
while(head!=null)
{
System.out.print(head.val+" ");
head=head.next;
}
System.out.println();
}
public static void main(String[]args){
ListNode head=new ListNode(1);
head.next=new ListNode(2);
head.next.next=new ListNode(3);
Solution s=new Solution();
s.PrintList(head);
s.PrintList(s.ReverseList(head));
}
}
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/f93e34e8440ddca8683714c0e7cf2440.png)