翻转链表——三种方法总结

方法一

将链表切成两段,左边是翻转后的链表,右边是待翻转链表,将原始链表中的头节点一个一个拼接到新链表头节点上

  1. public class Solution {
  2.     public ListNode ReverseList(ListNode head) {
  3.         ListNode pre = null; 
  4.         ListNode next = null;
  5.         while (head != null) {
  6.             next = head.next; 
  7.             head.next = pre;
  8.             pre = head;
  9.             head = next;
  10.         }
  11.         return pre;
  12.     }
  13. }

方法二

原位翻转,构建一个新的头节点dummy,然后依次将原始链表中的"头节点"插入到新的头节点dummy后面

  1. public class Solution {
  2.     public ListNode ReverseList(ListNode head) {
  3.         if(head == null || head.next == null)
  4.             return head;
  5.         ListNode dummy = new ListNode(-1);
  6.         dummy.next = head;
  7.         ListNode temp = head;
  8.         while(head.next != null){
  9.             temp = head.next;        
  10.             head.next = temp.next;
  11.             temp.next = dummy.next;
  12.             dummy.next = temp;
  13.         }
  14.         return dummy.next;
  15.     }
  16. }

方法三

递归,先递推到尾节点,然后依次执行翻转操作,返回翻转链表头节点

  1. public class Solution {
  2.     public ListNode ReverseList(ListNode head) {
  3.         if(head == null || head.next == null) 
  4.             return head;
  5.         ListNode pReverseNode = ReverseList(head.next);  //翻转后新链表的头节点
  6.         head.next.next = head;                                              //执行翻转操作
  7.         head.next = null;                                                        //去开始节点处的环
  8.         return pReverseNode;
  9.     }
  10. }

猜你喜欢

转载自blog.csdn.net/zhouqj1913/article/details/85028296