题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
分析
用一个指针记录当前位置,另外一个指针记录当前位置的前一个位置,以及另外一个指针记录下一个位置,然后遍历的过程中不停的改变当前位置的指针的next值
public class LinkNode {int val;LinkNode next;public LinkNode(int data) {this.val = data;this.next = null;}
}
public class LinkList {LinkNode head;public LinkList() {this.head = null;}public LinkNode getHead() {return this.head;}//添加元素public void addNode(int data) {LinkNode node = new LinkNode(data);if (this.head == null) {this.head = node;} else {LinkNode cur = this.head;while(cur.next != null) {cur = cur.next;}cur.next = node;}}//正序打印public void print(LinkNode node) {while(node != null) {System.out.print(node.val);System.out.print(" ");node = node.next;}System.out.println();}public void reverse() {LinkNode pre = null;LinkNode cur = this.head;while(cur != null) {LinkNode next = cur.next;cur.next = pre;pre = cur;cur = next;}print(pre);}
}
public class reverseLinkedList {public static void main(String[] args) {LinkList list = new LinkList();list.addNode(1);list.addNode(2);list.addNode(3);list.addNode(4);list.addNode(5);list.reverse();}
}