反转单链表

反转链表

反转一个单链表:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

迭代法

使用两个指针从头结点开始逐个改变方向,一次循环。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class solution{
   public ListNode solve(ListNode head){
   	 ListNode pre = null;
   	 ListNode cur = head;
   	 while(cur != null){
   			ListNode tmp = cur.next;
   			cur.next = pre;
   			pre = cur;
   			cur = tmp;
   	 }
   	return cur;
   }
}

递归

通过递归,从末尾向头结点逐个更改方向。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class solution{
   public ListNode solve(ListNode head){
   	// 递归终止条件:空链表或者递归到末尾
   	 if(head == null || head.next == null){
   	 	return head;
   	 }
   	 ListNode ans = solve(head.next);
   	 head.next.next = head;
   	 head.next = null;
   	 return ans; 
   }
}

温故知新,未央书斋

你可能感兴趣的:(后端相关,刷题笔记,链表,单链表)