1- 思路
- 定义三个指针
- prev:记录 cur 的前一个结点
- cur:记录当前需要翻转的结点
- tmp:记录 cur 的 next 防止遍历过程中找不到链表的剩余部分
2- 题解
⭐反转链表 ——题解思路
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode tmp = null;
while(cur!=null){
tmp = cur.next;
cur.next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
}
3-ACM模式
public class reverseLink {
static class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int x){
val = x;
}
}
public static ListNode reverse(ListNode head){
ListNode prev = null;
ListNode cur = head;
ListNode tmp = null;
while(cur!=null){
tmp = cur.next;
cur.next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入链表长度n");
int n = sc.nextInt();
ListNode head=null ,tail=null;
for(int i=0; i < n;i++){
ListNode newNode = new ListNode(sc.nextInt());
if(head==null){
head = newNode;
tail = newNode;
}else{
tail.next = newNode;
tail = newNode;
}
}
ListNode forRes = reverse(head);
System.out.println("翻转后的链表为:");
while(forRes!=null){
System.out.print(forRes.val+" ");
forRes = forRes.next;
}
}
}