206. 反转链表 - 力扣(LeetCode)
1.迭代
思路
这个题目很简单,最主要的就是了解链表的数据结构。
链表由多个节点构成,每个节点包括值与指针,其中指针指向下一个节点(单链表)。
方法就是将指针(next)指向前一个节点即可。我们设置old为前一个节点,current为当前节点,也就是让current.next=old即可。
具体代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode oldNode=null;
ListNode current = head;
while(current!=null){
ListNode temp = current.next;
current.next=oldNode;
oldNode=current;
current=temp;
}
return oldNode;
}
}