方法一
将链表切成两段,左边是翻转后的链表,右边是待翻转链表,将原始链表中的头节点一个一个拼接到新链表头节点上
- public class Solution {
- public ListNode ReverseList(ListNode head) {
- ListNode pre = null;
- ListNode next = null;
- while (head != null) {
- next = head.next;
- head.next = pre;
- pre = head;
- head = next;
- }
- return pre;
- }
- }
方法二
原位翻转,构建一个新的头节点dummy,然后依次将原始链表中的"头节点"插入到新的头节点dummy后面
- public class Solution {
- public ListNode ReverseList(ListNode head) {
- if(head == null || head.next == null)
- return head;
- ListNode dummy = new ListNode(-1);
- dummy.next = head;
- ListNode temp = head;
- while(head.next != null){
- temp = head.next;
- head.next = temp.next;
- temp.next = dummy.next;
- dummy.next = temp;
- }
- return dummy.next;
- }
- }
方法三
递归,先递推到尾节点,然后依次执行翻转操作,返回翻转链表头节点
- public class Solution {
- public ListNode ReverseList(ListNode head) {
- if(head == null || head.next == null)
- return head;
- ListNode pReverseNode = ReverseList(head.next); //翻转后新链表的头节点
- head.next.next = head; //执行翻转操作
- head.next = null; //去开始节点处的环
- return pReverseNode;
- }
- }