LeetCode 206. 反转链表 C++& java

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        // 思路1 : 每次取链表的最后一个元素 放到另一个空链表的开头
        //思路2 : 改变链表的指向
        //第一种思路就不实现了
               
        if(head == NULL)
            return NULL;
        else
        {
             ListNode* p ,*q;
            p = head ;
            q = head->next ;
            head->next = NULL ;
              while(q)
            {
                p = q ;
                q =  q->next ;
                p->next  = head ;
                head = p ;
            }          
        }
        return head ;   
    }
};

java 版 :       // 居然不用 指针 很神奇

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null ) return head ;
        ListNode p ,q ;
        p = head ;
        q= head.next ;
        head.next = null ;
        while(q!= null )
        {
            p = q ;
            q = q.next ;
            p.next = head ;
            head = p ;
        }  
        return head ;
    }
}






猜你喜欢

转载自blog.csdn.net/wx734518351/article/details/80457795