leetcode:(206) Reverse Linked List*(java)

题目:

    

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 解题思路:

      利用头插法,具体思路及代码如下:

   

package Leetcode_Github;
/**
 * 翻转链表:
 *
 */
public class DataStructure_LinkedList_206_1122 {
    public ListNode reverseList(ListNode head) {
        //定义一个新的节点,作为反转链表后新链表的头节点
        ListNode result=new ListNode(-1);
        while(head!=null){
            //将head.next保存,以防断链
            ListNode next=head.next;
            //将链表进行翻转
            head.next=result.next;
            result.next=head;

            head=next;
        }
        return result.next;
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/84336091