Flip a single linked list (note whether it contains a head node):
Idea one: Each time the node after the first node is placed in the first position. If there is no head node, an additional pointer is required to record the first nodes.
Code:
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode reverselist (ListNode head) {if(Head = =NULL) return NULL; if(Head.next = =NULL) returnHead; ListNode h=Head; while(head.next!=NULL) {ListNode P=Head.next; Head.next=P.next; P.next=h; H=p; } returnh; }}
Idea two: Create new space, use a pointer to traverse the original linked list, each time you insert the new node to the beginning of the new linked list, the code:
Public StaticListNode ReverseList1 (ListNode head) {//each time, the node behind the first node is placed behind the head node. if(Head = =NULL) return NULL; if(head.next==NULL) returnHead; ListNode h=NewListNode (Head.val); while(head.next!=NULL) {ListNode T=NewListNode (Head.val); T.next=h; Head=Head.next; } returnh; }
If there is a head junction:
Idea One:
Public StaticListNode reverselist (ListNode head) {//each time, the node behind the first node is placed behind the head node. if(Head = =NULL) return NULL; ListNode P=Head.next; while(p.next!=NULL) {ListNode Q=P.next; P.next=Q.next; Q.next=Head.next; Head.next=Q; } returnHead; }
Idea two:
Public StaticListNode ReverseList1 (ListNode head) {//each time, the node behind the first node is placed behind the head node. if(Head = =NULL) return NULL; if(head.next==NULL) returnHead; ListNode h=NewListNode (-1); H.next=NULL; ListNode P=Head.next; while(p!=NULL) {ListNode T=NewListNode (P.val); T.next=H.next; H.next=T; P=P.next; } returnh; }
Leetcoding--reverse Linked List (Java)