定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
public class Main {
static class ListNode{
int val;
ListNode next;
public ListNode(int val, ListNode next){
this.val = val;
this.next=next;
}
}
public static ListNode iterate(ListNode head){
ListNode prev=null;
ListNode curr=head;
while(curr!=null){
ListNode next=curr.next; //curr存储当前节点的下一个节点
curr.next=prev; //curr的下一个节点指向prev
prev=curr; //
curr=next;
}
return prev;
}
public static void main(String args[]){
ListNode Node5 = new ListNode(5,null);
ListNode Node4 = new ListNode(4,Node5);
ListNode Node3 = new ListNode(3,Node4);
ListNode Node2 = new ListNode(2,Node3);
ListNode Node1 = new ListNode(1,Node2);
ListNode prev = iterate(Node1);
System.out.println(prev);
}
}
递归
public class Main {
static class ListNode{
int val;
ListNode next;
public ListNode(int val, ListNode next){
this.val = val;
this.next=next;
}
}
public static ListNode recursion(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode new_head = recursion(head.next);
head.next.next = head;
head.next = null;
return new_head;
}
public static void main(String args[]){
ListNode Node5 = new ListNode(5,null);
ListNode Node4 = new ListNode(4,Node5);
ListNode Node3 = new ListNode(3,Node4);
ListNode Node2 = new ListNode(2,Node3);
ListNode Node1 = new ListNode(1,Node2);
ListNode prev = recursion(Node1);
System.out.println(prev);
}
}