题目
输入一个链表,反转链表后,输出新链表的表头。
思路
对于链表的反转,关键是处理好指针的指向问题。
例如将i的下一个结点由原来的j变为h,由于nowNode.next = preNode将i指向了h,导致链表在i处中断,那么在改变链表指向的时候,也要保存结点j。
那么在调整指针指向的时候,不仅要知道前一个结点,结点本身之外,也需要知道后一个结点,以防止链表断开。也就是说需要三个指针,分别指向当前遍历到的结点,它的前一个结点和后一个结点。
程序:
class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
public class subject15 {
public static ListNode ReverseList(ListNode head) {
ListNode preNode = null;
ListNode nowNode = head;
if(head == null) {//链表为空的情况
return null;
}
if(head.next == null) {//链表中只有一个元素的情况
return head;
}
while(nowNode != null) {
ListNode nextNode = nowNode.next;
nowNode.next = preNode;
preNode = nowNode;
nowNode = nextNode;
}
return preNode;
}
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
ListNode list2 = new ListNode(2);
ListNode list3 = new ListNode(3);
list1.next = list2;
list2.next = list3;
System.out.println(ReverseList(list1).val);
}
}