- 对于反转链表的思想感觉很别扭,需要多看,多想,克服困难
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode resultNode = null;
ListNode ahead = head;
ListNode before = null;
if(ahead == null || ahead.next ==null)
return ahead;;
while(ahead !=null){
ListNode nextNode = ahead.next;
if(nextNode==null)
resultNode = ahead;
ahead.next = before;
before = ahead;
ahead = nextNode;
}
return resultNode;
}
}
程序需要的变量:
1) 结果链表resultNode =null
2) 新的头结点ahead = head
3) 新的尾节点before = null
过程:
1、首先边界判断,如果只有一个节点或者没有节点,直接输出为原始链表ahead = head;
2、使用循环方式,依次的将原始链表节点进行翻转