leetCode206題,反轉單鏈表習題解答
package LinkList;
/**
* @Auther: DarkKing
* @Date: 2019/7/22 21:20
* @Description:
*/
public class LeetCode206 {
static class Solution {
public static ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode next;
while (cur != null) {
//獲取當前節點的下一個節點
next = cur.next;
//設置當前節點的前置節點
cur.next = pre;
//將當前節點設置爲前置節點
pre = cur;
//將下一個節點設置爲當前節點,繼續循環。
cur = next;
}
return pre;
}
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void main(String[] args) {
ListNode list= new ListNode(1);
list.next=new ListNode(2);
list.next.next=new ListNode(3);
list.next.next.next=new ListNode(4);
ListNode list2 = Solution.reverseList(list);
System.out.println(list2.toString());
}
}