- publicclass ListNode {
- int val;
- ListNode next = null;
- ListNode(int val) {
- this.val = val;
- }
- }
- publicclass Solution {
- public ListNode ReverseList(ListNode head) {
- if (head == null)
- returnnull;
- ListNode pPre = null ;
- ListNode pNext = null;
- while (head != null) {
- pNext = head.next;
- // reverse pointer
- head.next = pPre;
- // pointer moves down
- pPre = head;
- head = pNext;
- }
- // The head node of the new linked list is the tail node of the original linked list
- return pPre;
- }
- void printList(ListNode last) {
- while (last != null) {
- System.out.print(last.val + ",");
- last = last.next;
- }
- }
- publicstaticvoid main(String[] args) {
- ListNode head = new ListNode(1);
- head.next = new ListNode(4);
- head.next.next = new ListNode(3);
- head.next.next.next = new ListNode(2);
- Solution s = new Solution ();
- ListNode last = s.ReverseList(head);
- s.printList(last);
- }
- }
Java implements inputting a linked list, and after reversing the linked list, outputs all elements of the linked list.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325776838&siteId=291194637
Recommended
Ranking