题目简介
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
题目解释
就是有一个指针域指向下一个元素的节点,现在需要将这个指针域指向前一个元素。
题目解法
1.首先是使用数据结构之一——栈进行翻转。将节点塞进栈中,不断拿出来的同时将其指针域变为指向前一个节点的的位置,就能实现节点的翻转。代码如下
public ListNode reverseList(ListNode head) {
if(head == null )return head;
if(head.next == null)return head;
Stack<ListNode> stack = new Stack();
while(head != null){
ListNode tmp = head;
head = head.next;
tmp.next = null;
stack.push(tmp);
}
head = stack.pop();
ListNode h = new ListNode(1,head);
ListNode tmp = head;
while(!stack.isEmpty()){
tmp.next = stack.pop();
tmp = tmp.next;
}
return h.next;
}
这里容易出错的点在于栈是否有将所有节点全部收纳。如果发现最后结果只有一个节点,记得使用debug看看栈中元素是否全部收纳。
2.迭代法:使用双指针,设置pre和cur进行不停迭代。这里需要使用tmp记录下个一个节点值。代码如下
public ListNode reverseList(ListNode head) {
if(head == null )return head;
if(head.next == null)return head;
ListNode tmp = head.next;
ListNode cur = head;
ListNode pre = null;
cur.next = pre;
while(tmp != null){
pre = cur;
cur = tmp;
tmp = tmp.next;
cur.next = pre;
}
return cur;
}