topic:
Reverse a singly linked list.
Example:
Input: 1-> 2-> 3-> 4- > 5-> NULL
Output: 5-> 4-> 3-> 2- > 1-> NULL
A thought:
Reversed pointer, three pointers, pointing to the front after sequentially reversed pointer, head and tail point to the original
special cases should be noted: [], [1]
public ListNode reverseList(ListNode head) {
ListNode pre = head; //前一个指针
ListNode nex; //后一个指针
if(head == null) //处理输入空链表的情况
return head;
else
nex = head.next;
pre.next = null; //将原来的头节点变为尾节点,将他的next置空
while(nex != null){
head = nex;
nex = head.next; //移动指针
head.next = pre; //更改结点指针的指向,将指向后面的指针变为指向前面
pre = head;
}
return head;
}
Refer leetcode Gangster Comments
public static ListNode reverseListIterative(ListNode head) {
ListNode prev = null; //前指针节点
ListNode curr = head; //当前指针节点
//每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移
while (curr != null) {
ListNode nextTemp = curr.next; //临时节点,暂存当前节点的下一节点,用于后移
curr.next = prev; //将当前节点指向它前面的节点
prev = curr; //前指针后移
curr = nextTemp; //当前指针后移
}
return prev;
}
转自: https://leetcode-cn.com/problems/reverse-linked-list/comments/
Thinking two:
Method to create a head pointer forward runs, the original, traversing the list, the original to the new node is inserted one by one in the list
of this new method is actually not a new node, except the original node, the above new pointer a row order, forward runs by a method, a new sequence is achieved in reverse order of the original
public ListNode reverseList(ListNode head) {
ListNode new_head = null; //建立新指针
while(head != null){
ListNode tmp = head; //建立临时结点保存head
head = head.next; //head后移
tmp.next = new_head; //将tmp前插到新的链表中
new_head = tmp;
}
}
return new_head;
Thinking three:
Recursive, recursive directly to the end of the list, pointing to the tail of p, then treated with a head, and finally return to the first layer p
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head; //处理[],[1]两种情况,将head指针定位在原来链表尾结点的前一个结点,然后进行处理
ListNode p = reverseList(head.next); //将p定位在原来链表的尾部,不需要对p进行其他操作
head.next.next = head; // 反转链表指针
head.next = null;
return p;
}