反转链表(剑指offer-15)

方法1:递归

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12         if(head==null || head.next==null){
13             return head;
14         }
15         ListNode next = head.next;
16         ListNode newHead = ReverseList(next);//先反转后面的链表,从最后面两个节点开始反转,依次向前
17         next.next = head;//将后一个链表节点指向前一个节点
18         head.next = null;//将原链表中前一个节点指向后一个节点的指向关系断开
19        return newHead;
20     }
21 }

方法2:非递归(修改每个节点的next指向上一个节点)

 

 

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12 //第一步,定义引用pre指向null,cur指向头结点,cur代表当前结点,pre代表当前结点的上一个结点
13         ListNode pre = null;
14         ListNode cur = head;
15         //第二步,循环。先定义一个临时引用temp指向cur的下一个结点
16         ListNode temp = null;
17         while (cur != null) {
18             //(1)temp指向cur的下一个结点
19             temp = cur.next;
20             //(2)cur的next指向cur的上一个结点
21             cur.next = pre;
22             //(3)pre和cur右移,pre指向cur结点,cur指向temp结点
23             pre = cur;
24             cur = temp;
25         }
26         //循环结束后,cur和temp都指向null,pre指向原来链表的最后一个结点,此时为已经反转的链表的头结点
27         //第三步,head指向最后一个结点
28         head = pre;
29         return head;
30     }
31 }

 

方法3:头插法

 

 

 

 

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12         ListNode root = new ListNode(-1);//逻辑头节点位于-1的位置
13         ListNode next = null;//记录要处理的下一个节点
14         while(head != null){
15             next = head.next;// 记录要处理的下一个结点  1 2 3 4 5
16             head.next = root.next; // 当前结点的下一个结点指向逻辑头结点的下一个结点
17             root.next = head;// 逻辑头结点的下一个结点指向当前处理的结点
18             head = next;//开始处理下一个节点
19         }
20         return root.next;
21     }
22 }

 

posted @ 2020-07-01 21:27  10000_Hours  阅读(127)  评论(0编辑  收藏  举报